/****************************************************************************
*                                                                           *
* Copyright (c) RSC. All rights reserved(2010).								*
* Developer: Marius Ionescu    						*
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.Security;
using System.Web.UI.WebControls;
using NS_Controls;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.UI;
using AjaxControlToolkit;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text.RegularExpressions;

//TODO: show add link for new LabRequest while reviewing one...
public partial class LabRequest : SessionPageBase
{
    #region ViewState storage
    public int totalPage
    {
        get { return (int)(this.ViewState["totalPage"] ?? 1); }
        set { this.ViewState["totalPage"] = value; }
    }

    public int perPage
    {
        get { return (int)(this.ViewState["perPage"] ?? 1); }
        set { this.ViewState["perPage"] = value; }
    }

    public string requestID
    {
        get { return (string)(this.ViewState["requestID"] ?? ""); }
        set { this.ViewState["requestID"] = value; }
    }

    public string pacientID
    {
        get { return (string)(this.ViewState["pacientID"] ?? ""); }
        set { this.ViewState["pacientID"] = value; }
    }

    public string pacientName
    {
        get { return (string)(this.ViewState["pacientName"] ?? ""); }
        set { this.ViewState["pacientName"] = value; }
    }

    public string strExternalID
    {
        get { return (string)(this.ViewState["strExternalID"] ?? ""); }
        set { this.ViewState["strExternalID"] = value; }
    }

    public string strExternalType
    {
        get { return (string)(this.ViewState["strExternalType"] ?? ""); }
        set { this.ViewState["strExternalType"] = value; }
    }

    public string strRequestorID
    {
        get { return (string)(this.ViewState["strRequestorID"] ?? ""); }
        set { this.ViewState["strRequestorID"] = value; }
    }

    public string strMedicID
    {
        get { return (string)(this.ViewState["strMedicID"] ?? ""); }
        set { this.ViewState["strMedicID"] = value; }
    }

    public string paymentTypeID
    {
        get { return (string)(this.ViewState["paymentTypeID"] ?? ""); }
        set { this.ViewState["paymentTypeID"] = value; }
    }

    public bool submited
    {
        get { return (bool)(this.ViewState["submited"] ?? false); }
        set { this.ViewState["submited"] = value; }
    }

    public string strSectionCode
    {
        get { return (string)(this.ViewState["strSectionCode"] ?? ""); }
        set { this.ViewState["strSectionCode"] = value; }
    }

	public string strAnalyseClass
	{
		get { return (string)(this.ViewState["strAnalyseClass"] ?? ""); }
		set { this.ViewState["strAnalyseClass"] = value; }
	}

	public object requestedDate
	{
		get { return (this.ViewState["requestedDate"] != null ? (DateTime)this.ViewState["requestedDate"] : (object)DBNull.Value); }
		set { this.ViewState["requestedDate"] = DateTime.Parse(value.ToString()); }
	}

	public string strPriority
	{
		get { return (string)(this.ViewState["strPriority"] ?? ""); }
		set { this.ViewState["strPriority"] = value; }
	}

	public string requestGuid
	{
		get { return (string)(this.ViewState["requestGuid"] ?? ""); }
		set { this.ViewState["requestGuid"] = value; }
	}
	#endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
				//btnRequestSearch.Text = Resources.DatabaseStrings.btn_Search + " <span class='redFont'>(ALT+1)</span>";
				//btnSearchAnalyse.Text = Resources.DatabaseStrings.btn_Search + " <span class='redFont'>(ALT+2)</span>";
				//btnRequestAddAnalyse.Text = Resources.DatabaseStrings.btn_Add + " <span class='redFont'>(ALT+3)</span>";
				//btnRequestSaveAnalyse.Text = Resources.DatabaseStrings.btn_Save + " <span class='redFont'>(ALT+4)</span>";
				////btnBackInvestigation.Text = "Inapoi" + "<span class='redFont'>(ALT+5)</span>";
				//btnSaveModified.Text = Resources.DatabaseStrings.btn_Save + " <span class='redFont'>(ALT+6)</span>";
				//btnAddInvestigation.Text = Resources.DatabaseStrings.btn_Add + " <span class='redFont'>(ALT+7)</span>";
				//btnSaveInvestigation.Text = Resources.DatabaseStrings.btn_Save + " <span class='redFont'>(ALT+8)</span>";

				txtDataStart.Text = System.DateTime.Now.ToShortDateString();
                txtDataEnd.Text = System.DateTime.Now.ToShortDateString();
				calStartDateBulk.Format = DateFormat;
				calStartDateBulk2.Format = DateFormat;
				calEndDateBulk.Format = DateFormat;
				calEndDateBulk2.Format = DateFormat;

				LoadData();

				if (Request.QueryString["delete"] != null)
					DoResend();
				else
				{
					//create the checkGuid:
					requestGuid = System.Guid.NewGuid().ToString("N");
					//NB: N = no extra characters ; D = dashes ; B = braces ; P = parentheses
				}
				if (!string.IsNullOrEmpty(Request.QueryString["requestID"]))
					LoadLabRequest_Click(Request.QueryString["requestID"], Request.QueryString["pacientID"]);
            }

            if (IsPostBack)
            {
                CreateLinkButtons(totalPage);
            }
        }
        catch (Exception ex)
        {
            this.SetMessage("[PgLoad]" + ex.Message, true);
			output.Text = ex.ToString();
        }
    }

    protected void LoadData()
    {
        try
        {
            DataSet ds_Medic = Hipocrate.DB.DBConnection.GetData("select distinct id, FullName as name from vUsersAsMedics order by FullName");
            DataView dv0 = ds_Medic.Tables[0].DefaultView;

            drpMedic.DataSource = dv0;
            drpMedic.DataTextField = "name";
            drpMedic.DataValueField = "id";
            drpMedic.DataBind();
			strMedicBulk.DataSource = dv0;
			strMedicBulk.DataTextField = "name";
			strMedicBulk.DataValueField = "id";
			strMedicBulk.DataBind();
			drpMedic.Items.Insert(0, "");
			strMedicBulk.Items.Insert(0, "");

			DataSet ds_Sections = Hipocrate.DB.DBConnection.GetData("select code, name from sections where Active=1 order by name");
			//TODO: "Server.HTMLEncode"
            DataView dv1 = ds_Sections.Tables[0].DefaultView;

            drpSection.DataSource = dv1;
            drpSection.DataTextField = "name";
            drpSection.DataValueField = "code";
            drpSection.DataBind();
            drpSection.Items.Insert(0, "");

			string strSectii = "select distinct s.* from SECTIONS s ";

			//if checkSecLevel(SEC_ADMIN) OR checkSecLevel(SEC_LAB_ADMIN) OR checkSecLevel(SEC_ANALYSE_MANAGER) then
				strSectii += " where 1=1";
			//else
			//	strSectii += "inner join vUserSections gu on s.Code=gu.SectionCode " +
			//		"where GroupID in (" + Session("SQLUserGroups") + ")";

			//if not checkSecLevel(SEC_HOSPITAL_ADMIN) AND not checkSecLevel(SEC_REPORTS) AND _
			//        not (checkSecLevel(SEC_LAB_ADMIN) OR checkSecLevel(SEC_ANALYSE_MANAGER)) then
			//    if (Session("SectionType") &&& 2 == 2)
			//        strSectii += " and s.Ambulatory=1";
			//    if (Session("SectionType") &&& 4 == 4)
			//        strSectii += " and s.Guard=1";
			//    if (Session("SectionType") &&& 8 == 8)
			//        strSectii += " and s.Therapy=1";
			//    if (Session("SectionType") &&& 16 == 16)
			//        strSectii += " and s.Clinic=1";
			//else
				strSectii += " and (s.Ambulatory=1 or s.Guard=1 or s.Therapy=1 or s.Clinic=1)";
			strSectii += " order by s.Name";
			DataSet ds_LimitedSections = Hipocrate.DB.DBConnection.GetData(strSectii); //TODO: "Server.HTMLEncode"
			DataView dv1b = ds_Sections.Tables[0].DefaultView;
			
			strSectionBulk.DataSource = dv1b;
			strSectionBulk.DataTextField = "name";
			strSectionBulk.DataValueField = "code";
			strSectionBulk.DataBind();
			strSectionBulk.Items.Insert(0, "");
			//strSectionBulk.SelectedValue = Session("REGISTER_SECTION")

            ListItem lst_Oricare = new ListItem("Oricare", "-0");
            ListItem lst_NETERMINATA = new ListItem("NETERMINATA", "-4");
            ListItem lst_Netrimisa = new ListItem("Netrimisa", "-1");
            ListItem lst_Trimisa_Laborator = new ListItem("Trimisa in laborator", "0");
            ListItem lst_In_lucru = new ListItem("In lucru", "4");
            ListItem lst_Completata = new ListItem("Completata", "5");
            ListItem lst_Completata_Partial_Validata = new ListItem("Completata/Partial Validata", "7");
            ListItem lst_Terminata = new ListItem("Terminata !", "2");
            ListItem lst_Terminata2 = new ListItem("Terminata", "3");
            ListItem lst_Anulata = new ListItem("Anulata", "-2");
            ListItem lst_Proba_tehnica = new ListItem("Proba tehnica", "-3");

            drpStatus.Items.Insert(0, lst_Oricare);
            drpStatus.Items.Insert(1, lst_NETERMINATA);
            drpStatus.Items.Insert(2, lst_Netrimisa);
            drpStatus.Items.Insert(3, lst_Trimisa_Laborator);
            drpStatus.Items.Insert(4, lst_In_lucru);
            drpStatus.Items.Insert(5, lst_Completata);
            drpStatus.Items.Insert(6, lst_Completata_Partial_Validata);
            drpStatus.Items.Insert(7, lst_Terminata);
            drpStatus.Items.Insert(8, lst_Terminata2);
            drpStatus.Items.Insert(9, lst_Anulata);
            drpStatus.Items.Insert(10, lst_Proba_tehnica);

            DataSet ds_Domains = Hipocrate.DB.DBConnection.GetData("select distinct LD.ID, LD.Domain from LAB_DOMAINS LD where LD.Active=1 order by LD.Domain");
            DataView dv2 = ds_Domains.Tables[0].DefaultView;

            drpDomainInv.DataSource = dv2;
            drpDomainInv.DataTextField = "Domain";
            drpDomainInv.DataValueField = "id";
            drpDomainInv.DataBind();
            drpDomainInv.Items.Insert(0, "");

			string strDomenii = "select distinct [ID], [Domain] from LAB_DOMAINS where Active=1 ";
			//if not checkSecLevel(SEC_REPORTS) AND not checkSecLevel(SEC_ADMIN) then _
			//	strDomenii += "and Section='" & Replace(Session("Section"), "'", "''") & "' "
			strDomenii += " order by [Domain]";
			DataSet ds_LimitedDomains = ds_Domains; //Hipocrate.DB.DBConnection.GetData(strDomenii);
			DataView dv2b = ds_LimitedDomains.Tables[0].DefaultView;

			strLabDomainsBulk.DataSource = dv2b;
			strLabDomainsBulk.DataTextField = "Domain";
			strLabDomainsBulk.DataValueField = "id";
			strLabDomainsBulk.DataBind();
			strLabDomainsBulk.Items.Insert(0, new ListItem("Toate", "*"));

            drpPriority.Items.Insert(0, "");
            drpPriority.Items.Insert(1, "Urgenta");
            drpPriority.Items.Insert(2, "Normala");

            drpResults.Items.Insert(0, "");
            drpResults.Items.Insert(1, "NU");
            drpResults.Items.Insert(2, "DA");

            DataSet ds_Machines = Hipocrate.DB.DBConnection.GetData("select [id], [name] from MACHINE_TYPES order by [name]");
            DataView dv3 = ds_Machines.Tables[0].DefaultView;

            drpMachines.DataSource = dv3;
            drpMachines.DataTextField = "name";
            drpMachines.DataValueField = "id";
            drpMachines.DataBind();
            drpMachines.Items.Insert(0, "");

            DataSet ds_PaymentType = Hipocrate.DB.DBConnection.GetData("select ID, Name from PAYMENT_TYPES where Active=1 order by Name");
            DataView dv4 = ds_PaymentType.Tables[0].DefaultView;

            drpPayment.DataSource = dv4;
            drpPayment.DataTextField = "name";
            drpPayment.DataValueField = "id";
            drpPayment.DataBind();
            drpPayment.Items.Insert(0, "");

			SetAnalyseListVisibility(false);
			btnAddInvestigation.Visible = true;
        }
        catch (Exception ex)
        {
			this.SetMessage("[Data]" + ex.Message, true);
        }
    }

	/// <summary>
	/// Triggerred by: btnRequestSearch. Will search for LReqs in vListLabRequests.
	/// </summary>
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            divResultsSearch.Disabled = false;
            upProgressPag.Visible = true;
            divResultsSearch.Style.Add("display", "block");
			//SetAnalyseListVisibility(false);

			string sqlQuery = "select * from vListLabRequests L where 1=1";
            if (!string.IsNullOrEmpty(txtCodeRequest.Text))
                sqlQuery += " AND id = " + txtCodeRequest.Text;
            if (!string.IsNullOrEmpty(txtPacient.Text))
                sqlQuery += " AND (firstname like '%" + txtPacient.Text.Replace("'", "''") + "%' or lastname like '%" + txtPacient.Text.Replace("'", "''") + "%')";
            if (!string.IsNullOrEmpty(txtNameInv.Text))
                sqlQuery += " AND exists (select * from ANALYSE_TYPES A_T JOIN ANALYSES A ON A_T.ID=A.TypeID where A.RequestID=L.ID AND A_T.Name like '%" + txtNameInv.Text.Replace("'", "''") + "%')";
            if (!string.IsNullOrEmpty(txtFisa.Text))
                sqlQuery += " AND ExternalID = " + txtFisa.Text;
            if (!string.IsNullOrEmpty(drpMedic.SelectedValue))
                sqlQuery += " AND MedicID = " + drpMedic.SelectedValue;
            if (!string.IsNullOrEmpty(drpSection.SelectedValue))
                sqlQuery += " AND SectionCode = '" + drpSection.SelectedValue + "'";

            if (!string.IsNullOrEmpty(txtDataStart.Text) && !string.IsNullOrEmpty(txtDataEnd.Text))
                sqlQuery += " AND [RequestedDate] between CONVERT(SMALLDATETIME, '" + CommonSession.StareDiagramaIndicatori.GetDate(txtDataStart) + "', 103) AND DATEADD(D, 1, CONVERT(SMALLDATETIME, '" + CommonSession.StareDiagramaIndicatori.GetDate(txtDataEnd) + "', 103))";
            else if (!string.IsNullOrEmpty(txtDataStart.Text) && string.IsNullOrEmpty(txtDataEnd.Text))
                sqlQuery += " AND [RequestedDate] > CONVERT(SMALLDATETIME, '" + CommonSession.StareDiagramaIndicatori.GetDate(txtDataStart) + "', 103)";
            else if (string.IsNullOrEmpty(txtDataStart.Text) && !string.IsNullOrEmpty(txtDataEnd.Text))
                sqlQuery += " AND [RequestedDate] < DATEADD(D, 1, CONVERT(SMALLDATETIME, '" + CommonSession.StareDiagramaIndicatori.GetDate(txtDataEnd) + "', 103))";

            if (drpStatus.SelectedValue == "-1")
                sqlQuery += " AND submited=0 and DeletedID IS NULL";
            else if (drpStatus.SelectedValue == "0")
                sqlQuery += " AND submited=1";
            else if (drpStatus.SelectedValue == "4")
                sqlQuery += " AND RequestStatus=4";
            else if (drpStatus.SelectedValue == "5")
                sqlQuery += " AND (RequestStatus=5 or RequestStatus=7)";
            else if (drpStatus.SelectedValue == "7")
                sqlQuery += " AND RequestStatus=7";
            else if (drpStatus.SelectedValue == "2")
                sqlQuery += " AND RequestStatus=2";
            else if (drpStatus.SelectedValue == "3")
                sqlQuery += " AND RequestStatus=3";
            else if (drpStatus.SelectedValue == "-2")
            {
                sqlQuery += " AND DeletedID IS NOT NULL";
                divResultsSearch.Disabled = true;
            }
            else if (drpStatus.SelectedValue == "-3")
                sqlQuery += " AND Test=1";
            else if (drpStatus.SelectedValue == "-4")
                sqlQuery += " AND (RequestStatus <> 3 AND Submited=1)";

            if (!string.IsNullOrEmpty(drpDomainInv.SelectedItem.Text))
            {
                sqlQuery += " AND exists (SELECT * FROM vAnalyseMachines V join ANALYSES A on v.AnalyseID = A.TypeID";
                sqlQuery += " AND A.RequestID=L.ID";
                sqlQuery += " AND V.MachineClass = '" + drpDomainInv.SelectedItem.Text + "')";
            }

            if (!string.IsNullOrEmpty(drpPriority.SelectedValue))
                sqlQuery += " AND Priority = " + (drpPriority.SelectedIndex - 1);

            if (!string.IsNullOrEmpty(drpResults.SelectedValue))
            {
                if ((drpResults.SelectedIndex - 1) == 0)
                {
                    if (!string.IsNullOrEmpty(drpDomainInv.SelectedItem.Text))
                    {
                        sqlQuery += " AND NOT EXISTS (SELECT * FROM vAnalyseMachines V join ANALYSES A on v.AnalyseID = A.TypeID";
                        sqlQuery += " AND A.RequestID=L.ID AND A.Status>0 AND A.RequestID=L.ID";
                        sqlQuery += " AND V.MachineClass = '" + drpDomainInv.SelectedItem.Text + "')";
                    }
                    else
                        sqlQuery += " AND NOT EXISTS (select * from analyses A where A.RequestID=L.ID and A.Status>0)";
                }

                if ((drpResults.SelectedIndex - 1) == 1)
                {
                    if (!string.IsNullOrEmpty(drpDomainInv.SelectedItem.Text))
                    {
                        sqlQuery += " AND EXISTS (SELECT * FROM vAnalyseMachines V join ANALYSES A on v.AnalyseID = A.TypeID";
                        sqlQuery += " AND A.RequestID=L.ID AND A.Status>0 AND A.RequestID=L.ID";
                        sqlQuery += " AND V.MachineClass = '" + drpDomainInv.SelectedItem.Text + "')";
                    }
                    else
                        sqlQuery += " AND EXISTS (select * from analyses A where A.RequestID=L.ID and A.Status>0)";
                }
            }

            if (!string.IsNullOrEmpty(drpMachines.SelectedValue))
                sqlQuery += " AND EXISTS (SELECT * FROM vMachinesForAnalyse MFA inner join vMachinesList ML on ML.ID=MFA.MachineID where L.ID=MFA.Requestid and ML.TypeID=" + (drpMachines.SelectedValue) + ")";

            sqlQuery += " order by [RequestedDate] desc";

            DataSet ds_LabRequest = Hipocrate.DB.DBConnection.GetData(sqlQuery);
            DataView dv = ds_LabRequest.Tables[0].DefaultView;

            totalPage = dv.Count;
            CreateLinkButtons(dv.Count);

            DataSet ds_SystemConfig = GetSystemConfigDataSet();
            DataView dv1 = new DataView(ds_SystemConfig.Tables[0]);
            dv1.RowFilter = "Code = 'Sectiuni pe pagina'";
            perPage = Convert.ToInt32(dv1[0]["Name"]);

            int[] pages = GetPages(1, perPage, totalPage);
            if (CurrentPage >= pages.Length)
                CurrentPage = 0;

            PagedDataSource objPds = new PagedDataSource();
            objPds.DataSource = dv;
            objPds.AllowPaging = true;
            objPds.PageSize = perPage;
            objPds.CurrentPageIndex = CurrentPage;
            cmdPrev.Enabled = !objPds.IsFirstPage;
            cmdNext.Enabled = !objPds.IsLastPage;
            rptLabRequest.DataSource = objPds;
            rptLabRequest.DataBind();
            lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + objPds.PageCount.ToString();
        }
        catch (Exception ex)
        {
			this.SetMessage("[Search]" + ex.Message, true);
			output.Text = ex.ToString();
        }
    }

    protected void tabActive_TabChanged(object sender, EventArgs e)
    {
		//divResultsSearch.Style.Add("display", "block");
		//divDetailsRequest.Style.Add("display", "none");
		//divTestRequest.Style.Add("display", "none");
		//divModifyResults.Style.Add("display", "none");
		//divAddInvestigation.Style.Add("display", "none");
		divAddAnalyseRequest.Visible = (tabContainer.ActiveTabIndex == tabSpecificRequest.TabIndex) && btnSearchAnalyse.Visible;
		if (divAddAnalyseRequest.Visible)
			searchAnalyse(false);

		if ((tabContainer.ActiveTab == tabRequestBulkValidate) || (tabContainer.ActiveTab == tabRequestBulkClose))
			try
			{
				//restore tabpanel texts:
				tabRequestBulkValidate.HeaderText = tabRequestBulkValidate.ToolTip;
				tabRequestBulkClose.HeaderText = tabRequestBulkClose.ToolTip;
				//set main tabpanel to show what was selected:
				tabRequestBulk.HeaderText = tabContainer.ActiveTab.HeaderText;
				bulkProcessing.Text = tabRequestBulk.HeaderText.Substring(0, tabRequestBulk.HeaderText.IndexOf(' '));
				LabDomainsBulk.Visible = bulkProcessing.Text[0] == 'V';
				//"hide" selected panel:
				tabContainer.ActiveTab.HeaderText = "";
				tabContainer.ActiveTab = tabRequestBulk;
			}
			catch (Exception ex)
			{
				output.Text = ex.ToString();
			}
	}

	protected void LoadLabRequest_Click(string requestID, string pacientID)
	{
		LinkButton dummy = new LinkButton();
		dummy.CommandArgument = requestID;
		dummy.ToolTip = pacientID;
		LoadLabRequest_Click(dummy, null);
	}
	/// <summary>
	/// Triggerred by: lnkLabRequest. Retrieves LReq data from LAB_REQUESTS. Calls LoadDetailsRequest.
	/// </summary>
    protected void LoadLabRequest_Click(object sender, EventArgs e)
    {
		//output.Text += "showing button @ LoadLabRequest_Click. ";
		btnSaveInvestigation.Visible = true;
		try
        {
			//Pages/Hipocrate/Pacient.aspx
			//output.Text += "LoadLabRequest_Click, sender = '" + (sender ?? "null") + "'. Existing reqID = '" + requestID + "'. ";
			if ((sender != null) && (sender is LinkButton) && !string.IsNullOrEmpty((sender as LinkButton).CommandArgument))
			{
				requestID = (sender as LinkButton).CommandArgument;
				//output.Text += "Setting reqID to '" + requestID + "'. ";
				pacientID = (sender as LinkButton).ToolTip;
				RefreshJavaScriptLinks();
			}
			if(string.IsNullOrEmpty(requestID))
			{
				SetMessage("Date corupte.", true);
				return;
			}

			//tabSpecificRequest.Visible = true;
			tabSpecificRequest.HeaderText = "Cerere #" + requestID;
			tabContainer.ActiveTab = tabSpecificRequest;

			//divResultsSearch.Style.Add("display", "none");
            divDetailsRequest.Style.Add("display", "block");
            divTestRequest.Style.Add("display", "block");
			divModifyResults.Style.Add("display", "none");
			divAddInvestigation.Style.Add("display", "none");
			SetAnalyseListVisibility(false);

            btnRequestAddAnalyse.Visible = true;
            btnRequestSaveAnalyse.Visible = false;
            //btnAddInvestigation.Visible = false;
            //btnSaveInvestigation.Visible = false;

			Session[requestGuid] = requestID;
			//TODO: show permalink

            DataSet ds_Request = Hipocrate.DB.DBConnection.GetData(@"select distinct vAnalyses.Class, vAnalyses.RequestID,
					LD.ID as DomainID, LD.ScreenY,
					(select top 1 id from vAnalyses where Class=LD.Domain and RequestID =" + requestID + @") as [id],
					LV.ID as ValidationId, LD.CloseOnValidate
				FROM vAnalyses LEFT JOIN lab_domains LD on vAnalyses.Class = LD.Domain
				LEFT JOIN lab_validated LV on LV.RequestID = vAnalyses.RequestID and LV.DomainID = LD.ID
				where vAnalyses.RequestID = " + requestID +
                " order by LD.ScreenY, Class");
            DataView dv = ds_Request.Tables[0].DefaultView;

            rptTestRequest.DataSource = dv;
            rptTestRequest.DataBind();

            LoadDetailsRequest();

            string js = "hideShowGeneral();";
            ScriptManager.RegisterStartupScript(this, typeof(LabRequest), "hideShowGeneral", js, true);
        }
        catch (Exception ex)
        {
			if (sender == null)
				throw;
			this.SetMessage("[LReq]" + ex.Message, true);
			output.Text += "<br/><br/>" + ex.ToString();
        }
    }

	private void RefreshJavaScriptLinks()
	{
		pageReloadAddress.InnerHtml = Request.Path + "?requestId=" + requestID + "&pacientId=" + pacientID;
	}

	protected void TestRequest_Click(object sender, EventArgs e)
	{
		//TODO: implement TestRequest
		SetMessage("TestRequest not implemented", true);
	}

	private void DoValidation(LinkButton sender, int value)
	{
		try
		{
			//if (!javascript:confirm ("Din acest moment rezultatele venite pentru " + strDomain + " vor fi vizibile pe sectie.\nSunteti sigur ca doriti sa trimiteti rezultatele pe sectie?"))
			//    return;
			Hipocrate.DB.DBConnection.Execute("LabRequest_Expose",
				new string[] { "@intCodeID", "@strUserLogin", "@strVisibleClass", "@Value" },
				new object[] { sender.CommandArgument, Tools.userLogin, sender.ToolTip, value });
			Hipocrate.DB.DBConnection.Execute("Lab_Request_SetStatus", new string[] { "@RequestID" }, new object[] { requestID });
			if (value > 0)
				this.SetMessage("Din acest moment rezultatele venite pentru " + sender.ToolTip + " vor fi vizibile pe sectie.", false);
			else
				this.SetMessage("S-a revenit asupra validarii.", false);
			//up1.Update();
			LoadLabRequest_Click(sender.CommandArgument, pacientID);
			ScriptManager.RegisterStartupScript(this, typeof(LabRequest), "undoHideShowGeneral", "hideShowGeneral();", true);
		}
		catch (Exception ex)
		{
			this.SetMessage("[Validation]" + ex.Message, true);
			output.Text = ex.ToString();
		}
	}

	protected void Validate_Click(object sender, EventArgs e)
	{
		DoValidation(sender as LinkButton, 1);
	}
	protected void Invalidate_Click(object sender, EventArgs e)
	{
		DoValidation(sender as LinkButton, 0);
	}

    private void LoadDetailsRequest()
	{
		#region detalii pacient
		DataSet ds_DetailsPacient = Hipocrate.DB.DBConnection.GetData(
			@"select id,firstname, lastname, cnp, GrSang, rh, attention,
				Sex, datediff(Y, GetDate(), BirthDate) as Age, CIID
			from pacients where [id]=" + pacientID + "");
        DataView dv_Pacient = ds_DetailsPacient.Tables[0].DefaultView;

		pacientName = dv_Pacient[0]["lastName"].ToString() + " " + dv_Pacient[0]["firstName"].ToString();
		lblDetailsRequest.Text = "Detalii Cerere: <span class=\"redFontSmall\">(" + pacientName + "[" + pacientID + "])</span>";
		lblPacient.Text = "<span class=\"redFontSmall\">" + pacientName + "[" + pacientID + "]</span>";
		lblCNP.Text = dv_Pacient[0]["cnp"].ToString();

		lblGeneral.Text = "";
		if (!string.IsNullOrEmpty(dv_Pacient[0]["GrSang"].ToString()))
			lblGeneral.Text += dv_Pacient[0]["GrSang"].ToString();
		if (dv_Pacient[0]["rh"].ToString() == "1")
			lblGeneral.Text += "RH&nbsp;pozitiv; ";
		else if (dv_Pacient[0]["rh"].ToString() == "0")
			lblGeneral.Text += "RH&nbsp;negativ; ";

		if (dv_Pacient[0]["Sex"].ToString() == "True")
			lblGeneral.Text += "sex&nbsp;masculin;";
		else if (dv_Pacient[0]["Sex"].ToString() == "False")
			lblGeneral.Text += "sex&nbsp;feminin; ";
        else
			lblGeneral.Text += "sex&nbsp;nespecificat; ";

		#endregion

		DataSet ds_LabRequest = Hipocrate.DB.DBConnection.GetData(@"select LAB_REQUESTS.*,
					pt.Name as PaymentTypeName,death.MedicSuperviserID,
                    convert(varchar(10), death.RegistredDate, 103) deathReqDate,
                    convert(varchar(5),death.RegistredDate,108) as deathRecTime,
                     convert(varchar(20), RequestedDate, 113) RequestedDate,
                     convert(varchar(10), RequestedDate, 103) ReqDate,
                     convert(varchar(5), RequestedDate, 108) ReqTime,
                     convert(varchar(20), VisibleDate, 113) strVisibleDate,
                     convert(varchar(20), DeletedDate, 113) DeletedDate, DeletedID,
                     convert(varchar(20), CompletedDate, 113) CompletedDate
                    from LAB_REQUESTS
                    left join payment_types pt on LAB_REQUESTS.PaymentTypeID=pt.id
                    left join lab_deathrecords death on death.requestID=LAB_REQUESTS.id
                    where LAB_REQUESTS.[id]=" + requestID + "");
        DataView dv2 = ds_LabRequest.Tables[0].DefaultView;
		strExternalID = dv2[0]["ExternalID"].ToString();
		strExternalType = dv2[0]["ExternalType"].ToString();
		strRequestorID = dv2[0]["RequestorID"].ToString();
		paymentTypeID = dv2[0]["PaymentTypeID"].ToString();
		submited = Convert.ToBoolean(dv2[0]["PaymentTypeID"]);
		strSectionCode = dv2[0]["SectionCode"].ToString();
        submited = Convert.ToBoolean(dv2[0]["PaymentTypeID"]);
		requestedDate = dv2[0]["RequestedDate"].ToString();

        string sqlLabRequest;
        DataSet dsLRQ = null;

        if (strExternalType == "PA")
            sqlLabRequest = "";
        else if (strExternalType == "PR" || strExternalType == "P")
        {
            sqlLabRequest = "select sDeclaredDate as sDate, sDeclaredTime as sTime, SectionName, MedicFullName, MedicID from vPresentationFull where ID=" + strExternalID;
            dsLRQ = Hipocrate.DB.DBConnection.GetData(sqlLabRequest);
            strMedicID = dsLRQ.Tables[0].Rows[0]["MedicID"].ToString();
        }
        else if (strExternalType == "CI")
        {
            sqlLabRequest = "select sCIDate as sDate, sCITime as sTime, SectionName, MedicFullName, CIMedicID as MedicID from vCheckIn_LabRequests where CIID=" + strExternalID;
            dsLRQ = Hipocrate.DB.DBConnection.GetData(sqlLabRequest);
            strMedicID = dsLRQ.Tables[0].Rows[0]["MedicID"].ToString();
        }
        else if (strExternalType == "CU")
        {
            sqlLabRequest = "select sCUDate as sDate, sCUTime as sTime, SectionName, MedicFullName, CUMedic as MedicID from vCheckUpFull where CUID=" + strExternalID;
            dsLRQ = Hipocrate.DB.DBConnection.GetData(sqlLabRequest);
            strMedicID = dsLRQ.Tables[0].Rows[0]["MedicID"].ToString();
        }
        else if (strExternalType == "CO")
        {
            sqlLabRequest = "select sCODate as sDate, sCOTime as sTime, SectionName, MedicFullName, COMedicID as MedicID from vCheckOutFull where COID=" + strExternalID;
            dsLRQ = Hipocrate.DB.DBConnection.GetData(sqlLabRequest);
            strMedicID = dsLRQ.Tables[0].Rows[0]["MedicID"].ToString();
        }
        else
            sqlLabRequest = "";

        if (strExternalType == "PA")
            lblType.Text = "Fara tip";
		else if (strExternalType == "PR" || strExternalType == "P")
			lblType.Text = "<a class=\"redFont\" href='../Hipocrate/Pacient.aspx?pacientID=" + pacientID + "&action=admit&id=" + strExternalID + "'><b>Prezentare</b> [" + strExternalID + "]</a>";
		else if (strExternalType == "CI")
			lblType.Text = "<a class=\"redFont\" href='../Hipocrate/Pacient.aspx?pacientID=" + pacientID + "&action=checkin&id=" + strExternalID + "'><b>Internare</b> [" + strExternalID + "]</a>";
		else if (strExternalType == "CU")
			lblType.Text = "<a class=\"redFont\" href='../Hipocrate/Pacient.aspx?pacientID=" + pacientID + "&action=checkup&id=" + strExternalID + "'><b>Examinare</b> [" + strExternalID + "]</a>";
		else if (strExternalType == "CO")
			lblType.Text = "<a class=\"redFont\" href='../Hipocrate/Pacient.aspx?pacientID=" + pacientID + "&action=checkout&id=" + strExternalID + "'><b>Externare</b> [" + strExternalID + "]</a>";
        else
            lblType.Text = "NECUNOSCUT";

		if ((dsLRQ != null) && (dsLRQ.Tables.Count > 0))
        {
            lblDate.Text = dsLRQ.Tables[0].Rows[0]["sDate"].ToString() + " " + dsLRQ.Tables[0].Rows[0]["sTime"].ToString();
            lblMedic.Text = dsLRQ.Tables[0].Rows[0]["MedicFullName"].ToString();
            lblSection.Text = dsLRQ.Tables[0].Rows[0]["sectionName"].ToString();
        }

		if (!string.IsNullOrEmpty(strRequestorID))
		{
			string sqlRequestorID = "select isnull(lastname, '') + isnull(upper(' ' + firstname), '') as name from staff where id=" + strRequestorID;
			DataSet dsRequestor = Hipocrate.DB.DBConnection.GetData(sqlRequestorID);
			lblRequestor.Text = "<span class=\"redFont\">" + dsRequestor.Tables[0].Rows[0]["name"].ToString() + "</span>&nbsp;-&nbsp;" + dv2[0]["RequestedDate"].ToString() + "";
		}

		DataSet dsValidatorID = null;
		if (!string.IsNullOrEmpty(dv2[0]["DeletedDate"].ToString()))
        {
            lblValAnul.Text = "Anulata";
            string sqlRequestordeletedID = "select isnull(lastname, '') + isnull(upper(' ' + firstname), '') as name from staff where id=" + dv2[0]["DeletedID"].ToString();
			DataSet dsStatusRequestor = Hipocrate.DB.DBConnection.GetData(sqlRequestordeletedID);
            if (dsStatusRequestor.Tables.Count > 0)
                lblStatus.Text = "<span class=\"redFont\">" + dsStatusRequestor.Tables[0].Rows[0]["name"].ToString() + "</span>&nbsp;-&nbsp;" + dv2[0]["DeletedDate"].ToString() + "";
            else
                lblStatus.Text = "INEXISTENT" + "&nbsp;-&nbsp;" + dv2[0]["DeletedDate"].ToString() + "";
        }
        else
        {
            string sqlValidatorID = @"select convert(varchar(20), LS.ValidationDate, 113) ValidationDate, LS.ValidatorID, LS.SectionCode from LAB_SECTIONS LS 
                                where LS.RequestID=" + requestID;
            dsValidatorID = Hipocrate.DB.DBConnection.GetData(sqlValidatorID);
			string validatorID = null;
			if (dsValidatorID.Tables[0].Rows.Count > 0)
				validatorID = dsValidatorID.Tables[0].Rows[0]["ValidatorID"].ToString();
			if (string.IsNullOrEmpty(validatorID))
			{
				lblValAnul.Text = "Nevalidata";
			}
			else
			{
				lblValAnul.Text = "Validata";
				string sqlRequestordeletedID = @"select isnull(lastname, '') + isnull(upper(' ' + firstname), '') as name
											from staff where id=" + validatorID;
				DataSet dsStatusRequestor = Hipocrate.DB.DBConnection.GetData(sqlRequestordeletedID);

				string strValidatorsString = @"<SPAN STYLE='WIDTH: 200px'>" + dsStatusRequestor.Tables[0].Rows[0]["name"].ToString() + "</SPAN>" +
					"&nbsp;-&nbsp;" + dsValidatorID.Tables[0].Rows[0]["ValidationDate"].ToString() +
					"&nbsp;, " + dsValidatorID.Tables[0].Rows[0]["SectionCode"].ToString();

				lblStatus.Text = strValidatorsString;
			}

            if (!string.IsNullOrEmpty(dv2[0]["CompletedDate"].ToString()))
            {
                lblCompleted.Text = "&nbsp;PROCESATA&nbsp;-&nbsp;" + dv2[0]["CompletedDate"].ToString();
            }
            else
            {
                if (!string.IsNullOrEmpty(dv2[0]["DeletedDate"].ToString()))
                    lblCompleted.Text = "ANULATA";
                else if (!string.IsNullOrEmpty(dv2[0]["strVisibleDate"].ToString()))
                    lblCompleted.Text = "Trimisa pe sectie";
                else if (!string.IsNullOrEmpty(dv2[0]["ClosedID"].ToString()))
                    lblCompleted.Text = "<font class='error'>INCHISA</font>";
                else if (dsValidatorID.Tables.Count > 0)
                    lblCompleted.Text = "Validata pentru executie";
                else if (!string.IsNullOrEmpty(dv2[0]["Submited"].ToString()))
                    lblCompleted.Text = "Trimisa spre executie";
                else
                    lblCompleted.Text = "<font class='blueFont'>Nu va fi procesata, nefiind inca trimisa spre executie!</font>";
            }
        }

        chkProbeTech.Checked = (dv2[0]["Test"].ToString() == "True");
		chkAchitat.Checked = (dv2[0]["IsPayed"].ToString() == "True");

		strPriority = dv2[0]["Priority"].ToString();
        if (dv2[0]["Submited"].ToString() != "True")
        {
			if (strPriority == "0")
                plcUrgenta.Controls.Add(new LiteralControl("<input type=\"checkbox\" class=\"box\" name=\"strPriority\" value=\"0\" checked=\"checked\" ID=\"Checkbox1\">"));
        }
        else
        {
			if (strPriority == "0")
                lblUrgenta.Text = "<font color=red><b>DA</b></font>";
			else if (strPriority == "1")
                lblUrgenta.Text = "<font color=Blue>Minima</font>";
            else
                lblUrgenta.Text = "NU";
        }

        txtWeight.Text = NumericValue(dv2[0]["Weigth"], 3);
		txtHeight.Text = NumericValue(dv2[0]["Height"], 2);

        lblDateRequest.Text = dv2[0]["ReqDate"].ToString() + "&nbsp" + dv2[0]["ReqTime"].ToString();

        foreach (ListItem li in drpPayment.Items)
        {
            if (0 == String.Compare(li.Value, paymentTypeID))
                drpPayment.SelectedValue = li.Value;
        }

        //if (dv2[0]["Submited"].ToString() != "True")
        txtRegister.Text = dv2[0]["PaymentNo"].ToString();

        txtChitanta.Text = dv2[0]["nrChit"].ToString();

        string sqlDeathDate = @"select RecordDeathData from lab_sections ls left join sections s on ls.sectioncode=s.code where requestid=" + requestID;
        DataSet ds_DeathDate = Hipocrate.DB.DBConnection.GetData(sqlDeathDate);
        DataView dvDeathDate = ds_DeathDate.Tables[0].DefaultView;
		if ((dvDeathDate.Count > 0) && (dvDeathDate[0]["RecordDeathData"].ToString() == "0"))
        {
            string sqlMedicSurviver = @"select ID,LastName+ ' ' + FirstName as MedicName  from staff s where s.sectioncode<>'EXT' and exists 
                                        (select * from staffpositions sp left join positions p on sp.PosCode=p.code 
                                        where (p.code='MEDIC' or p.code='MED') and s.id=sp.staffid)";
            DataSet ds_MedicSurviver = Hipocrate.DB.DBConnection.GetData(sqlMedicSurviver);
            DataView dvMedicSurviver = ds_MedicSurviver.Tables[0].DefaultView;

            drpMedicSurviver.DataSource = dvMedicSurviver;
            drpMedicSurviver.DataTextField = "medicname";
            drpMedicSurviver.DataValueField = "id";
            drpMedicSurviver.DataBind();
            drpMedicSurviver.Items.Insert(0, "");

            foreach (ListItem li in drpMedicSurviver.Items)
            {
                if (0 == String.Compare(li.Value, dv2[0]["MedicSuperviserID"].ToString()))
                    drpMedicSurviver.SelectedValue = li.Value;
            }

            trDeath.Style.Add("display", "block");
            plcDeath.Controls.Add(drpMedicSurviver);
            plcDeath.Controls.Add(new LiteralControl(dv2[0]["deathReqDate"].ToString() + "&nbsp" + dv2[0]["deathRecTime"].ToString()));
        }

        string sqlPacientSex = @"select Sex, datediff(Y, GetDate(), BirthDate) as Age, CIID from pacients where [id]=" + pacientID;
        DataSet ds_PacientSex = Hipocrate.DB.DBConnection.GetData(sqlPacientSex);
        DataView dvPacientSex = ds_PacientSex.Tables[0].DefaultView;

        if (dvPacientSex[0]["sex"].ToString() != "True")
        {
            trSex.Style.Add("display", "block");
			//NB: take care when changing the display to update the btnSaveInvestigation_Click below
            if (dv2[0]["IsPregnant"].ToString() == "True")
                lblInsarcinata.Text = "<font color=red><b>DA</b></font>";
            else
                lblInsarcinata.Text = "NU";
        }

        if (dv2[0]["Submited"].ToString() != "True")
        {
            trSection.Style.Add("display", "block");
            string sqlCodeSection = @"select distinct s.code, s.name from sections s join lab_domains l on s.code=l.section where l.active=1 and s.Active=1 order by s.name";
            DataSet ds_CodeSection = Hipocrate.DB.DBConnection.GetData(sqlCodeSection);
            DataView dvCodeSection = ds_CodeSection.Tables[0].DefaultView;

            string sqlCountSection = @"select count(*) as NR from vAnalysesSelected v join lab_domains l on v.Class=l.Domain where v.RequestID=35464 and l.Section=
                                '" + dvCodeSection[0]["code"].ToString() + "'";
            DataSet ds_CountSection = Hipocrate.DB.DBConnection.GetData(sqlCountSection);
            DataView dvCountSection = ds_CountSection.Tables[0].DefaultView;

            string sqlNameSection = @"select * from lab_sections where requestID=
                                " + requestID + " and SectionCode='" + dvCodeSection[0]["code"].ToString() + "'";
            DataSet ds_NameSection = Hipocrate.DB.DBConnection.GetData(sqlNameSection);
            DataView dvNameSection = ds_NameSection.Tables[0].DefaultView;

            plcSection.Controls.Add(new LiteralControl("<input name=\"strSections\" id=\"strSections\" type=\"checkbox\" checked=\"checked\" value=\" " + dvCodeSection[0]["code"].ToString() + "\" ><label for=\"strSections\">&nbsp;<b>" + dvCodeSection[0]["name"].ToString() + "</b></label>"));
        }

        if (!string.IsNullOrEmpty(dv2[0]["Description"].ToString()))
        {
            trinfSupl.Style.Add("display", "block");
            txtDescription.Text = dv2[0]["Description"].ToString();
        }
		txtSentDiags.Text = dv2[0]["SentDiags"].ToString();

        string sqlstrPreviousCT = @"select * from LAB_SECTIONS where RequestID=" + requestID + " AND SectionCode='CT'";
        DataSet ds_strPreviousCT = Hipocrate.DB.DBConnection.GetData(sqlstrPreviousCT);
        DataView dvstrPreviousCT = ds_strPreviousCT.Tables[0].DefaultView;

        if (dv2[0]["Submited"].ToString() != "True")
        {
            trCheckIN.Style.Add("display", "block");

            if (dv2[0]["CheckedIn"].ToString() == "True")
                lblCheckedIn.Text = "DA";
            else
                lblCheckedIn.Text = "NU";

            if (dv2[0]["OtherDiagsOff"].ToString() == "True")
                lblOtherDiagsOff.Text = "DA";
            else
                lblOtherDiagsOff.Text = "NU";
        }

        if (dv2[0]["Submited"].ToString() != "True")
        {
            trExamenCRT.Style.Add("display", "block");

            if (dv2[0]["PreviousCT"].ToString() == "True")
                lblPreviousCT.Text = "DA";
            else
                lblPreviousCT.Text = "NU";

            if (dv2[0]["IodOK"].ToString() == "True")
                lblIodOK.Text = "DA";
            else
                lblIodOK.Text = "NU";
        }

        txtCommnets.Text = dv2[0]["Comments"].ToString();
        txtDiagnostic.Text = dv2[0]["ResponseDiags"].ToString();

        string sqlQuickLnk = @"select L.ID, CONVERT(VARCHAR(6), L.RequestedDate, 113) as ReqDate from lab_requests L 
                    where L.PacientID=" + pacientID + " AND L.[ID]<>" + requestID + " AND EXISTS (select * from lab_sections LS where ls.RequestID=L.[ID])";

        DataSet ds_QuickLnk = Hipocrate.DB.DBConnection.GetData(sqlQuickLnk);
        DataView dvQuickLnk = ds_QuickLnk.Tables[0].DefaultView;

        for (int i = 0; i < dvQuickLnk.Count; i++)
        {
            plkQuickLink.Controls.Add(new LiteralControl("&nbsp;" + dvQuickLnk[i]["ID"].ToString() + "&nbsp;"));
        }

        if (!string.IsNullOrEmpty(paymentTypeID))
        {
            string sqlRequestCost = @"select SUM(ISNULL(Qty, 0)*ISNULL(Price, 0)) as analyseCost from vAnalyseType_Costs 
            join analyses on vAnalyseType_Costs.ID=analyses.TypeID 
            where requestID=" + requestID + " AND CONVERT(DATETIME, '" + ((DateTime)(dv2[0]["RequestedDate"])).ToString("dd/MM/yyyy") + "' , 103) between startDate AND ISNULL(endDate, GetDate()) " +
            " AND (endDate IS NULL OR GetDate() between startDate AND endDate)" +
            " AND analyses.PaymentTypeID= " + paymentTypeID + " AND vAnalyseType_Costs.PaymentTypeID=" + paymentTypeID;

            DataSet ds_RequestCost = Hipocrate.DB.DBConnection.GetData(sqlRequestCost);
            DataView dvRequestCost = ds_RequestCost.Tables[0].DefaultView;

			if (dvRequestCost.Count > 0)
			{
				object dbCost = dvRequestCost[0]["AnalyseCost"];
				if (dbCost == DBNull.Value) dbCost = 0;
				lblCosts.Text = Convert.ToDouble(dbCost).ToString();
			}
			else
				lblCosts.Text = "";
        }
        else
        {
            string sqlRequestCostAnalyse = @"select TypeID, PaymentTypeID from ANALYSES where RequestID=" + requestID;

            DataSet ds_RequestCostAnalyse = Hipocrate.DB.DBConnection.GetData(sqlRequestCostAnalyse);
            DataView dvRequestCostAnalyse = ds_RequestCostAnalyse.Tables[0].DefaultView;

            double tmpCostAnalyse = 0;

            for (int i = 0; i < dvRequestCostAnalyse.Count; ++i)
            {
                tmpCostAnalyse += getTotalCost(dvRequestCostAnalyse[i]["TypeID"].ToString(), dv2[i]["RequestedDate"].ToString(), dv2[i]["PaymentTypeID"].ToString());
            }
			//TODO: show tmpCostAnalyse on page...
        }
    }
	private string NumericValue(object value, int precision)
	{
		if (value == DBNull.Value)
			return string.Empty;
		return Decimal.Parse(value.ToString()).ToString("N" + precision);
	}

    private double getTotalCost(string analyseID, string requestDate, string PTID)
    {
        string sqlRequestCost = @"select SUM(ISNULL(Qty, 0)*ISNULL(Price, 0)) as analyseCost from vAnalyseType_Costs where ID=" + analyseID +
            "join analyses on vAnalyseType_Costs.ID=analyses.TypeID";

        if (!string.IsNullOrEmpty(requestDate))
            sqlRequestCost += " AND CONVERT(DATETIME, '" + requestDate + "' , 103) between startDate AND ISNULL(endDate, GetDate())";
        else
            sqlRequestCost += " AND (endDate IS NULL OR GetDate() between startDate AND endDate)";

        sqlRequestCost += " AND PaymentTypeID= " + PTID;

        DataSet ds_RequestCost = Hipocrate.DB.DBConnection.GetData(sqlRequestCost);
        DataView dvRequestCost = ds_RequestCost.Tables[0].DefaultView;

        double tempCost = Convert.ToDouble(dvRequestCost[0]["AnalyseCost"]);
        return tempCost;
    }

    private DataSet GetSystemConfigDataSet()
    {
        DataSet ds_SystemConfig = (DataSet)Session["ds_SystemConfig"];
        if (ds_SystemConfig == null)
        {
            ds_SystemConfig = Hipocrate.DB.DBConnection.GetData("System_Config_Select", new string[] { }, new object[] { });
            Session["ds_SystemConfig"] = ds_SystemConfig;
        }
        return ds_SystemConfig;
	}

	#region pagination
	private void CreateLinkButtons(int tPage)
    {
        try
        {
            DataSet ds_SystemConfig = GetSystemConfigDataSet();
            DataView dv = new DataView(ds_SystemConfig.Tables[0]);
            dv.RowFilter = "Code = 'Sectiuni pe pagina'";

            tblPagination.Controls.Clear();

            int[] pages = GetPages(1, Convert.ToInt32(dv[0]["Name"]), tPage);
            if (pages.Length == 1)
                return;

            TableRow tblRowPag = new TableRow();
            TableCell tblCellPag = new TableCell();

            tblCellPag.Wrap = false;
            tblCellPag.CssClass = "tdn_perfect";
            tblCellPag.Controls.Add(new LiteralControl("Pagina: "));

            tblCellPag.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            tblCellPag.Controls.Add(NewLinkButton("linkFst", false, "|&lt;", "First", 0));
            tblCellPag.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));

            if (pages.Length > perPage)
            {
                CreatePaginationLinks(ref tblCellPag, 0, 4);
                tblCellPag.Controls.Add(NewSeparator());
                if (5 < CurrentPage - 5)
                {
                    tblCellPag.Controls.Add(new LiteralControl("..."));
                    tblCellPag.Controls.Add(NewSeparator());
                }
                CreatePaginationLinks(ref tblCellPag, Math.Max(5, CurrentPage - 5), Math.Min(CurrentPage + 5, pages.Length - 1));
                tblCellPag.Controls.Add(NewSeparator());
                if (CurrentPage + 6 < pages.Length - 5)
                {
                    tblCellPag.Controls.Add(new LiteralControl("...")); tblCellPag.Controls.Add(NewSeparator());
                }
                CreatePaginationLinks(ref tblCellPag, Math.Max(CurrentPage + 6, pages.Length - 5), pages.Length - 1);
            }
            else
                CreatePaginationLinks(ref tblCellPag, 0, pages.Length - 1);

            tblCellPag.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));
            tblCellPag.Controls.Add(NewLinkButton("linkLst", false, "&gt;|", "Last", 0));
            tblCellPag.Controls.Add(new LiteralControl("&nbsp;&nbsp;"));

            tblCellPag.Controls.Add(new LiteralControl(" din " + pages.Length));

            tblRowPag.Cells.Add(tblCellPag);
            tblPagination.Rows.Add(tblRowPag);
        }

        catch (Exception ex)
        {
			this.SetMessage("[Buttons]" + ex.Message, true);
        }
    }

    private LiteralControl NewSeparator()
    {
        return new LiteralControl("  &middot;  ");
    }

    private void CreatePaginationLinks(ref TableCell target, int firstPage, int lastPage)
    {
        for (int k = firstPage; k <= lastPage; ++k)
        {
            if (k > firstPage) target.Controls.Add(NewSeparator());
            target.Controls.Add(NewLinkButton("link" + (k + 1).ToString(), CurrentPage == k, (k + 1).ToString(), "Numbered", k));
        }
    }

    private LinkButton NewLinkButton(string id, bool disabled, string text, string cmdName, int cmdArgument)
    {
        LinkButton result = new LinkButton();
        result.ID = id;
        result.CssClass = "aLink";
        result.Style.Add("text-decoration", "none");
        result.Font.Bold = disabled;
        result.Enabled = !disabled;
        result.Text = text;
        result.CausesValidation = false;
        result.Command += new CommandEventHandler(NavigationLink_Click);
        result.CommandName = cmdName;
        result.CommandArgument = cmdArgument.ToString();
        return result;
    }

    void NavigationLink_Click(Object sender, CommandEventArgs e)
    {
        try
        {
            switch (e.CommandName)
            {
                case "First": CurrentPage = 0;
                    break;
                case "Last": CurrentPage = (int)Math.Ceiling((double)totalPage / perPage) - 1;
                    break;
                case "Next": CurrentPage = CurrentPage + 1;
                    break;
                case "Prev": CurrentPage = CurrentPage - 1;
                    break;
                case "Numbered":
                    CurrentPage = Int32.Parse(e.CommandArgument.ToString());
                    break;
                default:
                    return;
            }
            btnSearch_Click(null, null);
        }
        catch (Exception ex)
        {
			this.SetMessage("[Navigation]" + ex.Message, true);
        }
    }

    public int[] GetPages(int currentPage, int rowsPerPage, int totalRows)
    {
        double tempTotRows = totalRows;
        double tempRowsPerPage = rowsPerPage;
        double tempTotPages = Math.Ceiling((tempTotRows / rowsPerPage));
        int totalPages;
        totalPages = (int)tempTotPages;
        int[] pg = new int[totalPages];

        for (int k = 0; k < (int)tempTotPages; k++)
        {
            pg[k] = k + 1;
        }

        return pg;
    }

    public int CurrentPage
    {
        get
        {
            object o = this.ViewState["_CurrentPage"];
            if (o == null)
                return 0;
            else
                return (int)o;
        }

        set
        {
            this.ViewState["_CurrentPage"] = value;
        }
    }

    protected void cmdPrev_Click(object sender, System.EventArgs e)
    {
        if (CurrentPage > 0)
            --CurrentPage;
        btnSearch_Click(null, null);
    }

    protected void cmdNext_Click(object sender, System.EventArgs e)
    {
        ++CurrentPage;
        btnSearch_Click(null, null);
	}
	#endregion

	protected string getID(string id, string deletedID)
    {
        if (string.IsNullOrEmpty(deletedID))
            return "<span>" + id + "</span>";
        else
            return "<span class=\"redFont\">" + id + "</span>";
    }

    protected string getStatus(string status, string submited, string deletedid)
    {
        if (status == "-4")
            return "NETERMINATA";
        else if ((status == "-1" || string.IsNullOrEmpty(status) || submited == "False") && string.IsNullOrEmpty(deletedid))
            return "<span class=\"blueFont\">>>Netrimisa<<</span>";
        else if (status == "0")
            return "Trimisa in laborator";
        else if ((status == "4" || status == "6") && string.IsNullOrEmpty(deletedid))
            return "<b>In lucru</b>";
        else if (status == "5")
            return "Completata";
        else if (status == "7")
            return "Completata/Partial Validata";
        else if (status == "2")
            return "Terminata <span class=\"redFont\"><b>!</b></span>";
        else if (status == "3")
            return "Terminata";
        else if (status == "-2" || !string.IsNullOrEmpty(deletedid))
            return "Anulata";
        else if (status == "-3")
            return "Proba tehnica";
        else
            return "Oricare";
    }

    protected string getPriority(string priority)
    {
        if (priority == "0")
            return "Maxima";
        else if (priority == "1")
            return "Normala";
        else if (priority == "2")
            return "Minima";
        else
            return "";
    }

	protected string getPacient(string pacient)
	{
		DataSet ds_Pacient = Hipocrate.DB.DBConnection.GetData("select firstname, lastname from pacients where [id]=" + pacient);
		DataView dv = ds_Pacient.Tables[0].DefaultView;

		return dv[0]["lastName"].ToString() + " " + dv[0]["firstName"].ToString();
	}

	/// <summary>
	/// Method that populates the lnkButtonMedic foreground.
	/// </summary>
	/// <param name="medic">The MedicID from the db.</param>
	/// <returns>The given medic's name.</returns>
    protected string getMedic(string medic)
    {
		if (string.IsNullOrEmpty(medic))
			//throw new ApplicationException("No medic id supplied...");
			return "";
        DataSet ds_Pacient = Hipocrate.DB.DBConnection.GetData("select isnull(lastname, '') + isnull(upper(' ' + firstname), '') as name from staff where id=" + medic);
        DataView dv = ds_Pacient.Tables[0].DefaultView;

        return dv[0]["name"].ToString();
    }

    protected void RequestRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        RepeaterItem item = e.Item;
        if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
        {
			DataRowView drv = (DataRowView)item.DataItem;

			LinkButton lnkValidate = (LinkButton)item.FindControl("lnkValidate");
			lnkValidate.Visible = (drv["ValidationId"] == DBNull.Value);
			LinkButton lnkInvalidate = (LinkButton)item.FindControl("lnkInvalidate");
			lnkInvalidate.Visible = !lnkValidate.Visible; //TODO: && bCanDevalidate
			LinkButton lnkModifyResults = (LinkButton)item.FindControl("lnkModifyResults");
			//TODO: enable lnkModifyResults depending on: drv["CloseOnValidate"]
			
			PlaceHolder plcAnalyze = (PlaceHolder)item.FindControl("plcHolder");

            string nameAnalyse = drv[0].ToString();

            string sql = "select vAnalyses.*,LD.ID as DomainID from vAnalyses left join LAB_DOMAINS LD on vAnalyses.Class=LD.Domain where vAnalyses.RequestID =" + requestID +
                            " AND class = '" + nameAnalyse + "' order by LD.ScreenY, class, vAnalyses.ScreenY, [name]";
            DataSet ds_Analyse = Hipocrate.DB.DBConnection.GetData(sql);

            DataView dv = ds_Analyse.Tables[0].DefaultView;

            for (int i = 0; i < dv.Count; ++i)
            {
                plcAnalyze.Controls.Add(new LiteralControl("<tr>"));
                plcAnalyze.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 5%\">&nbsp;"));
                plcAnalyze.Controls.Add(new LiteralControl("</td>"));
                plcAnalyze.Controls.Add(new LiteralControl("<td style=\"width: 50%\">"));
				#region add Analyse title row (and deletion button)
                plcAnalyze.Controls.Add(new LiteralControl("<table style=\"width: 100%\"><tr><td align=\"left\" class=\"tdn\"><span class=\"blueFont\"><b>"));
                plcAnalyze.Controls.Add(new LiteralControl(dv[i]["Name"].ToString() + "</b></span>"));
                plcAnalyze.Controls.Add(new LiteralControl("</td><td align=\"right\">"));
				plcAnalyze.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 5%\">"));
				if (lnkValidate.Visible)
				{
					plcAnalyze.Controls.Add(new LiteralControl("<a href=\"#\">"));
					plcAnalyze.Controls.Add(new LiteralControl("<img onclick=\"AskDeleteAnalyse(" + requestID + ", " + dv[i]["ID"].ToString() + ")\" src=\"" + Request.ApplicationPath + "/Images/Btn/delete.gif\" border=\"0\" />"));
					plcAnalyze.Controls.Add(new LiteralControl("</a>"));
				}
				else
					plcAnalyze.Controls.Add(new LiteralControl("&nbsp;"));
				plcAnalyze.Controls.Add(new LiteralControl("</td></tr></table>"));
				#endregion
				#region add Rest of table
				draw_Reference(plcAnalyze, dv[i]["ID"].ToString());
				#endregion
				plcAnalyze.Controls.Add(new LiteralControl("</td>"));
				plcAnalyze.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 40%\">&nbsp;"));
				plcAnalyze.Controls.Add(new LiteralControl("</td>"));
                plcAnalyze.Controls.Add(new LiteralControl("</tr>"));
            }
        }
    }

	[WebMethod]
	public static void DeleteAnalyse(string requestId, string analyseID, string strBI)
	{
		bool? bidirectional = string.IsNullOrEmpty(strBI) ? (bool?)null : bool.Parse(strBI);
		//string strRepeat = Request.QueryString["Repeat"]; //NB: not sent
		//TODO: begin tran
		Hipocrate.DB.DBConnection.Execute("LabRequest_Resend",
			new string[] { "@strRequestID", "@strAnalyseID", "@strBI", "@strUserLogin" // , "@Repeat"
			},
			new object[] { requestId, analyseID, bidirectional, Tools.userLogin // , string.IsNullOrEmpty(strRepeat) ? (bool?)null : bool.Parse(strRepeat)
			});
		Hipocrate.DB.DBConnection.Execute("Lab_Request_SetStatus", new string[] { "@RequestID" }, new object[] { requestId });
		//TODO: if no errors, commit, else rollback and alert
	}

    protected void draw_Reference(PlaceHolder plc, string analyseID)
    {
		if (string.IsNullOrEmpty(pacientID))
			throw new ApplicationException("Empty PacientID!");
        string sql = "select rnv.MinValue,rnv.MaxValue,*, Reportable = 0 from vResults_List v " +
            "left join pacients p on p.id = " + pacientID +
            "left join REF_NORMAL_VALUES rnv on rnv.refid=v.refid and rnv.sex=p.sex and " +
            "Datediff(year,p.BirthDate,GetDate()) >= rnv.ageLo and Datediff(year,p.BirthDate,GetDate()) < rnv.ageHi " +
            "where analyseID = " + analyseID + " AND RefsActive = 1";

		DataSet ds_Analyse = Hipocrate.DB.DBConnection.GetData(sql, false);

        DataView dv = ds_Analyse.Tables[0].DefaultView;

        if (dv.Count > 0)
        {
            plc.Controls.Add(new LiteralControl("<table width=\"100%\">"));
            plc.Controls.Add(new LiteralControl("<tr class=\"tdh\">"));
            plc.Controls.Add(new LiteralControl("<th style=\"width: 20%\">Cod</th>"));
            plc.Controls.Add(new LiteralControl("<th style=\"width: 15%\">Valoare</th>"));
            plc.Controls.Add(new LiteralControl("<th style=\"width: 15%\">Min</th>"));
            plc.Controls.Add(new LiteralControl("<th style=\"width: 15%\">Max</th>"));
			plc.Controls.Add(new LiteralControl("<th style=\"width: 20%\">Comentarii</th>"));
			plc.Controls.Add(new LiteralControl("<th style=\"width: 15%\">&nbsp;</th>"));
			plc.Controls.Add(new LiteralControl("</tr>"));

            decimal stringValue;
            decimal maxValue;
            decimal minValue;

            for (int i = 0; i < dv.Count; ++i)
            {
                plc.Controls.Add(new LiteralControl("<tr>"));

                bool bStringValue = decimal.TryParse(dv[i]["StringValue"].ToString().Replace(".", ","), out stringValue);
                bool bMaxValue = decimal.TryParse(dv[i]["MaxValue"].ToString().Replace(".", ","), out maxValue);
                bool bMinValue = decimal.TryParse(dv[i]["MinValue"].ToString().Replace(".", ","), out minValue);

                bool redGreenSpan = false;
                if (stringValue > maxValue || stringValue < minValue)
                    redGreenSpan = true;
                else
                    redGreenSpan = false;

                if (bStringValue)
                    stringValue = Convert.ToDecimal(dv[i]["StringValue"].ToString().Replace(".", ","));
                else
                    stringValue = 0;

                if (bMaxValue)
                    maxValue = Convert.ToDecimal(dv[i]["MaxValue"].ToString().Replace(".", ","));
                else
                    maxValue = 0;

                if (bMinValue)
                    minValue = Convert.ToDecimal(dv[i]["MinValue"].ToString().Replace(".", ","));
                else
                    minValue = 0;

                plc.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 20%\">"));
                if (redGreenSpan)
                    plc.Controls.Add(new LiteralControl("<span class=\"redFont\">"));
                else
                    plc.Controls.Add(new LiteralControl("<span class=\"greenFont\">"));
                plc.Controls.Add(new LiteralControl(dv[i]["Name"].ToString()));
                plc.Controls.Add(new LiteralControl("</span>"));
                plc.Controls.Add(new LiteralControl("</td>"));

                plc.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 20%\">"));
                if (redGreenSpan)
                    plc.Controls.Add(new LiteralControl("<span class=\"redFont\"><b>"));
                else
                    plc.Controls.Add(new LiteralControl("<span class=\"greenFont\"><b>"));
                plc.Controls.Add(new LiteralControl(dv[i]["StringValue"].ToString()));
                plc.Controls.Add(new LiteralControl("</b></span>"));
                plc.Controls.Add(new LiteralControl("</td>"));

                plc.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 20%\">"));
                if (redGreenSpan)
                    plc.Controls.Add(new LiteralControl("<span class=\"redFont\"><b>"));
                else
                    plc.Controls.Add(new LiteralControl("<span class=\"greenFont\"><b>"));
                plc.Controls.Add(new LiteralControl(dv[i]["MinValue"].ToString()));
                plc.Controls.Add(new LiteralControl("</b></span>"));
                plc.Controls.Add(new LiteralControl("</td>"));

                plc.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 20%\">"));
                if (redGreenSpan)
                    plc.Controls.Add(new LiteralControl("<span class=\"redFont\"><b>"));
                else
                    plc.Controls.Add(new LiteralControl("<span class=\"greenFont\"><b>"));
                plc.Controls.Add(new LiteralControl(dv[i]["MaxValue"].ToString()));
                plc.Controls.Add(new LiteralControl("</b></span>"));
                plc.Controls.Add(new LiteralControl("</td>"));

                plc.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 20%\">"));
                if (redGreenSpan)
                    plc.Controls.Add(new LiteralControl("<span class=\"redFont\"><b>"));
                else
                    plc.Controls.Add(new LiteralControl("<span class=\"greenFont\"><b>"));
                plc.Controls.Add(new LiteralControl(dv[i]["Comments"].ToString()));
                plc.Controls.Add(new LiteralControl("</span>"));
                plc.Controls.Add(new LiteralControl("<b></td>"));
				plc.Controls.Add(new LiteralControl("<tr>"));
            }

            plc.Controls.Add(new LiteralControl("</table>"));
        }
    }

	/// <summary>
	/// Stergere rezultate analize.
	/// </summary>
	private void DoResend()
	{
		string strRequestID = Request.QueryString["requestID"];
		string checkGuid = Request.QueryString["checkGuid"];
		if (!strRequestID.Equals(Session[checkGuid]))
		{
			//Response.Redirect(Request.ApplicationPath + "/Default.aspx", true);
			SetMessage("Mismatched RequestIDs!", true);
			output.Text = "From QS: '" + strRequestID + "', should've been: '" + Session[checkGuid] + "'";
			return;
		}
		DeleteAnalyse(Request.QueryString["delete"], strRequestID, Request.QueryString["bidrectional"]);
		//up1.Update();
	}

    protected void btnAddRequestAnalyse_Click(object sender, EventArgs e)
    {
		divAddAnalyseRequest.Visible = true;
		SetAnalyseListVisibility(true);
		
		btnRequestAddAnalyse.Visible = false;
        btnRequestSaveAnalyse.Visible = true;
        //btnRequestSearch.Visible = false;
        btnSaveModified.Visible = false;
        //btnAddInvestigation.Visible = false;
		//output.Text += "hiding button @ btnAddRequestAnalyse_Click. ";
        btnSaveInvestigation.Visible = false;
		//divResultsSearch.Style.Add("display", "none");
        divDetailsRequest.Style.Add("display", "none");
        divTestRequest.Style.Add("display", "none");

		divModifyResults.Style.Add("display", "none");
        divAddInvestigation.Style.Add("display", "none");

        btnBackInvestigation.Visible = true;

        DataSet ds_InvestigationClass = Hipocrate.DB.DBConnection.GetData("select distinct LD.ID, LD.Domain as [name] from LAB_DOMAINS LD where LD.Active=1 order by LD.Domain");
        DataView dv1 = ds_InvestigationClass.Tables[0].DefaultView;

        drpClassInvestigation.DataSource = dv1;
        drpClassInvestigation.DataTextField = "name";
        drpClassInvestigation.DataValueField = "id";
        drpClassInvestigation.DataBind();
        drpClassInvestigation.Items.Insert(0, "");

        DataSet ds_InvestigationGroup = Hipocrate.DB.DBConnection.GetData("select distinct ID, UPPER([name]) as [name] from ANALYSE_GROUPS where active=1 order by [name]");
        DataView dv2 = ds_InvestigationGroup.Tables[0].DefaultView;

        drpGroupInvestigation.DataSource = dv2;
        drpGroupInvestigation.DataTextField = "name";
        drpGroupInvestigation.DataValueField = "id";
        drpGroupInvestigation.DataBind();
        drpGroupInvestigation.Items.Insert(0, "");

        DataSet ds_Probes = Hipocrate.DB.DBConnection.GetData("select s.id, s.name from SAMPLE_TYPES s order by s.name");
        DataView dv3 = ds_Probes.Tables[0].DefaultView;

        drpProbe.DataSource = dv3;
        drpProbe.DataTextField = "name";
        drpProbe.DataValueField = "id";
        drpProbe.DataBind();
        drpProbe.Items.Insert(0, "");

        searchAnalyse(false);
    }

	private void SetAnalyseListVisibility(bool visible)
	{
		divAddAnalyseRequest.Style.Add("display", visible ? "block" : "none");
		btnSearchAnalyse.Visible = visible;
	}

    protected void btnSearchAnalyse_Click(object sender, EventArgs e)
    {
        searchAnalyse(false);
    }

    protected void searchAnalyse(bool bSave)
    {
        string sqlAnalyseSelect = @"select distinct [Name], groupName, class, multiple, LD.ScreenY, c.Qty from vAnalysesNotSelected V left join 
            LAB_DOMAINS LD on v.Class = LD.Domain LEFT OUTER JOIN 
            vCostsPrice c ON v.TypeID  = c.AnalyseID AND PaymentTypeID = 2
            where 1=1"
//            + @"AND exists (select * from LAB_DOMAINS LD join LAB_SECTIONS LS on LD.Section=LS.SectionCode 
//            where LD.Domain=V.Class AND LS.RequestID=" + requestID + ")"
			;

        if (!submited)
            sqlAnalyseSelect += @" AND V.IsPrintable=1 AND not exists (select * from ANALYSE_RESTRICTED_SECTIONS ARS
            where ARS.AnalyseTypeID=v.TypeID AND ARS.SectionCode='" + strSectionCode + "') ";

        sqlAnalyseSelect += @" AND NOT EXISTS (SELECT * FROM vAnalysesSelected A where 
            (A.typeID=V.typeID OR (A.[Name]=V.[Name] AND A.Class=V.Class AND A.GroupID=V.GroupID AND (A.Multiple=V.Multiple OR A.Multiple=0)))
             AND requestID = " + requestID +
            ") AND NOT EXISTS (SELECT * FROM ANALYSES A where A.typeID=V.typeID AND requestID = " + requestID + ") ";

        if (!string.IsNullOrEmpty(txtNameInvestigation.Text))
            sqlAnalyseSelect += " AND (groupName like '%" + txtNameInvestigation.Text + "%' or [Name] like '%%') ";
        if (!string.IsNullOrEmpty(drpGroupInvestigation.SelectedItem.Text))
            sqlAnalyseSelect += " AND GroupName='" + drpGroupInvestigation.SelectedItem.Text + "' ";
        if (!string.IsNullOrEmpty(drpClassInvestigation.SelectedItem.Text))
            sqlAnalyseSelect += " AND class = '" + drpClassInvestigation.SelectedItem.Text + "' ";
        if (!string.IsNullOrEmpty(drpProbe.SelectedItem.Text))
            sqlAnalyseSelect += " AND sampleTypeID='" + drpProbe.SelectedItem.Text + "' ";

        sqlAnalyseSelect += @"order by LD.ScreenY,class, GroupName, [Name]";

        DataSet ds_AnalyseSelect = Hipocrate.DB.DBConnection.GetData(sqlAnalyseSelect);
        DataView dv_AnalyseSelect = ds_AnalyseSelect.Tables[0].DefaultView;

//this.SetMessage(dv_AnalyseSelect.Count.ToString() + " analyses @ " + DateTime.Now.ToString("yyyy-MM-dd.HH:mm:ss"), false);
//output.Text = sqlAnalyseSelect;
        plcAnalyseAdd.Controls.Add(new LiteralControl("<table border=\"0\" width=\"100%\"><tr class=\"tdh\"><td style=\"width: 100%\" colspan=\"3\">"));
        string tempClass = ""; string tempGroup = ""; int count = 0; bool drawTR = true; int countDRV = 0; int countDVClass = 0; int tmpcountDVClass = 0;

        foreach (DataRowView drv in dv_AnalyseSelect)
        {
            if (tempClass != drv["class"].ToString())
            {
                plcAnalyseAdd.Controls.Add(new LiteralControl("<tr class=\"tdh\"><td style=\"width: 100%\" colspan=\"3\">"));
                tempClass = drv["class"].ToString();
                tempGroup = drv["groupName"].ToString();
                plcAnalyseAdd.Controls.Add(new LiteralControl(tempClass + "[<span class=\"greenFont\">" + tempGroup + "</span>]"));
                plcAnalyseAdd.Controls.Add(new LiteralControl("</td></tr>"));
                count = 0;

                dv_AnalyseSelect.RowFilter = "class = '" + tempClass + "'";
                countDVClass = dv_AnalyseSelect.Count;
                tmpcountDVClass = 0;
            }

            if (count > 2 || drawTR)
            {
                plcAnalyseAdd.Controls.Add(new LiteralControl("<tr>"));
                drawTR = false;
            }

            if (count > 2)
            {
                drawTR = false;
                count = 0;
            }

            count++;
            countDRV++;
            tmpcountDVClass++;

            if (countDVClass % 3 == 1 && tmpcountDVClass == countDVClass)
            {
                plcAnalyseAdd.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 33%\" colspan=\"3\">"));
            }
            else if (countDVClass % 3 == 2 && tmpcountDVClass == countDVClass)
            {
                plcAnalyseAdd.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 33%\" colspan=\"2\">"));
            }
            else
                plcAnalyseAdd.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 33%\">"));

            CheckBox chk = new CheckBox();
            chk.Checked = false;
            chk.ID = "chkA" + countDRV;
            chk.Text = drv["name"].ToString();
            plcAnalyseAdd.Controls.Add(chk);
            plcAnalyseAdd.Controls.Add(new LiteralControl("</td>"));

            if (count > 2 || drawTR)
                plcAnalyseAdd.Controls.Add(new LiteralControl("</tr>"));
        }

        plcAnalyseAdd.Controls.Add(new LiteralControl("</table>"));


        string sqlAnalyseSelected = @"select distinct v.[Name], v.groupName, v.class, LD.ScreenY from vAnalysesSelected v 
            left join LAB_DOMAINS LD on v.Class = LD.Domain where v.requestID = " + requestID +
            "order by LD.ScreenY, v.class, v.GroupName, v.[Name]";
        DataSet ds_AnalyseSelected = Hipocrate.DB.DBConnection.GetData(sqlAnalyseSelected);
        DataView dv_AnalyseSelected = ds_AnalyseSelected.Tables[0].DefaultView;

        plcAnalyseRemove.Controls.Add(new LiteralControl("<table border=\"0\" width=\"100%\"><tr class=\"tdh\"><td style=\"width: 100%\" colspan=\"3\">"));
        string tempClassS = ""; string tempGroupS = ""; int countS = 0; bool drawTRS = true; int countDRVS = 0; int countDVClassS = 0; int tmpcountDVClassS = 0;

        foreach (DataRowView drv in dv_AnalyseSelected)
        {
            if (tempClassS != drv["class"].ToString())
            {
                plcAnalyseRemove.Controls.Add(new LiteralControl("<tr class=\"tdh\"><td style=\"width: 100%\" colspan=\"3\">"));
                tempClassS = drv["class"].ToString();
                tempGroupS = drv["groupName"].ToString();
                plcAnalyseRemove.Controls.Add(new LiteralControl(tempClassS + "[<span class=\"greenFont\">" + tempGroupS + "</span>]"));
                plcAnalyseRemove.Controls.Add(new LiteralControl("</td></tr>"));
                countS = 0;

                dv_AnalyseSelected.RowFilter = "class = '" + tempClassS + "'";
                countDVClassS = dv_AnalyseSelected.Count;
                tmpcountDVClassS = 0;
            }

            if (countS > 2 || drawTRS)
            {
                plcAnalyseRemove.Controls.Add(new LiteralControl("<tr>"));
                drawTRS = false;
            }

            if (countS > 2)
            {
                drawTRS = false;
                countS = 0;
            }

            countS++;
            countDRVS++;
            tmpcountDVClassS++;

            if (countDVClassS % 3 == 1 && tmpcountDVClassS == countDVClassS)
            {
                plcAnalyseRemove.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 33%\" colspan=\"3\">"));
            }
            else if (countDVClassS % 3 == 2 && tmpcountDVClassS == countDVClassS)
            {
                plcAnalyseRemove.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 33%\" colspan=\"2\">"));
            }
            else
                plcAnalyseRemove.Controls.Add(new LiteralControl("<td class=\"tdn\" style=\"width: 33%\">"));

            CheckBox chkS = new CheckBox();
            chkS.Checked = true;
            chkS.ID = "chkR" + countDRVS;
            chkS.Text = drv["name"].ToString();
            plcAnalyseRemove.Controls.Add(chkS);
            plcAnalyseRemove.Controls.Add(new LiteralControl("</td>"));

            if (countS > 2 || drawTRS)
                plcAnalyseRemove.Controls.Add(new LiteralControl("</tr>"));
        }

        plcAnalyseRemove.Controls.Add(new LiteralControl("</table>"));

		#region save
		if (bSave)
        {
			//output.Text += "saving ReqID " + requestID + ".";
            try
            {
                //int n = Hipocrate.DB.DBConnection.Execute("Analyse_RemoveLogic", new string[] { "@intCodeID", "@strUserLogin" }, new object[] { requestID, Tools.userLogin });

                foreach (Control ctrl in plcAnalyseAdd.Controls)
                {
                    if (ctrl is CheckBox)
                    {
						//output.Text += ctrl.UniqueID + "(" + (ctrl as CheckBox).Text + ") - '" + this.Request.Form[ctrl.UniqueID] + "'. ";
						///restore value from before postback:
                        (ctrl as CheckBox).Checked = "on".Equals(this.Request.Form[ctrl.UniqueID]);
						if ((ctrl as CheckBox).Checked == true)
						{
							object result_newID = Hipocrate.DB.DBConnection.ExecuteSPWithInOutParams("Analyse_Add",
								new string[] { "@strRequestID", "@strName", "@strUserLogin" },
								new object[] { requestID, (ctrl as CheckBox).Text, Tools.userLogin }, "@strOUT")[0].Value;
							//output.Text += string.Format("Analyse_Add({0}, '{1}', '{2}'). ", requestID, (ctrl as CheckBox).Text, Tools.userLogin);
						}
                    }
                }

                foreach (Control ctrl in plcAnalyseRemove.Controls)
                {
                    if (ctrl is CheckBox)
                    {
                        (ctrl as CheckBox).Checked = "on".Equals(this.Request.Form[ctrl.UniqueID]);
						if ((ctrl as CheckBox).Checked == false)
						{
							int result = Hipocrate.DB.DBConnection.Execute("Analyse_RemoveDeleted",
								new string[] { "@strRequestID", "@strName", "@strUserLogin" },
								new object[] { requestID, (ctrl as CheckBox).Text, Tools.userLogin });
						}
                    }
                }

                //int resultStatus = Hipocrate.DB.DBConnection.Execute("Lab_Request_SetStatus", new string[] { "@RequestID" }, new object[] { requestID });

                plcAnalyseAdd.Controls.Clear();
                plcAnalyseRemove.Controls.Clear();

                this.SetMessage("Datele au fost salvate.", false);
            }
            catch (Exception ex)
            {
				this.SetMessage("[Analyse]" + ex.Message, true);
            }
		}
		#endregion
	}

    protected void btnSaveRequestAnalyse_Click(object sender, EventArgs e)
    {
        searchAnalyse(true);
        btnAddRequestAnalyse_Click(null, null);
    }

    protected void tabAnalyseActive_TabChanged(object sender, EventArgs e)
    {
        searchAnalyse(false);
    }

    protected void btnBackInvestigation_Click(object sender, EventArgs e)
    {
		SetAnalyseListVisibility(false);
        btnBackInvestigation.Visible = false;
        btnRequestSearch.Visible = true;
        btnSaveModified.Visible = false;
		LoadLabRequest_Click(null, EventArgs.Empty);
		ScriptManager.RegisterStartupScript(this, typeof(LabRequest), "undoHideShowGeneral", "hideShowGeneral();", true);
	}

    protected void ModifyResults_Click(object sender, EventArgs e)
    {
        LinkButton lnk = sender as LinkButton;
        strAnalyseClass = lnk.CommandArgument;

        lblModify.Text = "Modificare rezultate pentru cererea: " + requestID;

		//divResultsSearch.Style.Add("display", "none");
        divDetailsRequest.Style.Add("display", "none");
        divTestRequest.Style.Add("display", "none");
        divModifyResults.Style.Add("display", "block");
		SetAnalyseListVisibility(false);

        btnRequestAddAnalyse.Visible = false;
        btnRequestSaveAnalyse.Visible = false;
        btnRequestSearch.Visible = true;
        btnBackInvestigation.Visible = true;
        btnSaveModified.Visible = true;
        //btnAddInvestigation.Visible = false;
		//output.Text += "hiding button @ ModifyResults_Click. ";
		btnSaveInvestigation.Visible = false;

        DataSet dsSexAGe = Hipocrate.DB.DBConnection.GetData(@"SELECT P.Sex, ABS(datediff(YY, P.BirthDate, GetDate())) as Age FROM PACIENTS P 
            WHERE P.[ID]=(SELECT PacientID from Lab_Requests L where L.[ID]=" + requestID + ")");
        string sexP = Convert.ToString(dsSexAGe.Tables[0].Rows[0]["Sex"]);
        string ageP = Convert.ToString(dsSexAGe.Tables[0].Rows[0]["Age"]);

        DataSet dsIsPregnant = Hipocrate.DB.DBConnection.GetData(@"SELECT L.IsPregnant from Lab_Requests L where L.[ID]= " + requestID);
        string IsPregnant = "";
        if (dsIsPregnant.Tables.Count > 0)
            IsPregnant = Convert.ToString(dsIsPregnant.Tables[0].Rows[0]["IsPregnant"]);
		//TODO: show IsPregnant in page?

        ModifyResults(false, strAnalyseClass);
    }

    protected void ModifyResults(bool bSave, string AnalyseClass)
    {
        try
        {
            string sqlModifySelect = @"select * from vRefs_EditManual where RequestID =" + requestID + " and class='" + AnalyseClass + "' order by ATScreenY, MachineTypeName, ScreenX, ScreenY, RefName";
            DataSet ds_ModifySelect = Hipocrate.DB.DBConnection.GetData(sqlModifySelect);
            DataView dv_ModifySelect = ds_ModifySelect.Tables[0].DefaultView;

            plcModifyResults.Controls.Add(new LiteralControl("<table border=\"0\" width=\"100%\"><tr class=\"tdh\"><td style=\"width: 35%\">Nume</td><td style=\"width: 35%\">Valoare</td><td style=\"width: 35%\">Comentarii</td></tr>"));
            string tempClass = "";
            DataSet ds_Results = null;
            DataView dv_Results = null;
            string sqlResults = "";

            foreach (DataRowView drv in dv_ModifySelect)
            {
                if (tempClass != drv["AnalyseName"].ToString())
                {
                    plcModifyResults.Controls.Add(new LiteralControl("<tr class=\"tdhAlternate\"><td style=\"width: 100%\" colspan=\"3\">"));
                    tempClass = drv["AnalyseName"].ToString();
                    plcModifyResults.Controls.Add(new LiteralControl(tempClass));
                    plcModifyResults.Controls.Add(new LiteralControl("</td></tr>"));
                }

                sqlResults = @"select [ID], stringValue, Comments from Results where AnalyseID =" + drv["AnalyseID"].ToString() + " and RefID=" + drv["RefID"].ToString();
                ds_Results = Hipocrate.DB.DBConnection.GetData(sqlResults);
                dv_Results = ds_Results.Tables[0].DefaultView;

                plcModifyResults.Controls.Add(new LiteralControl("<tr class=\"tdn\">"));
                plcModifyResults.Controls.Add(new LiteralControl("<td style=\"width: 35%\">"));
                plcModifyResults.Controls.Add(new LiteralControl("<b>" + drv["RefName"].ToString() + "</b><span class=\"redFont\">(Istoric)</span>"));
                plcModifyResults.Controls.Add(new LiteralControl("</td>"));
                plcModifyResults.Controls.Add(new LiteralControl("<td style=\"width: 35%\">"));
                DropDownList drp = new DropDownList();

                switch (drv["ValueType"].ToString())
                {
                    case "INT":
                        {
                            TextBox txt = new TextBox();
                            txt.ID = "txtINT" + drv["RefID"].ToString();
                            txt.Width = 100;
                            if (dv_Results.Count > 0)
                                txt.Text = dv_Results[0]["stringValue"].ToString();
                            plcModifyResults.Controls.Add(txt);
                            if (drv["UMName"] != System.DBNull.Value)
                                plcModifyResults.Controls.Add(new LiteralControl("<span class=\"redFont\">" + drv["UMName"].ToString().Replace("[", "<").Replace("]", ">") + "</span>"));
                            break;
                        }

                    case "LST":
                        {
                            drp.ID = "drpLST" + drv["RefID"].ToString();
                            drp.Width = 300;
                            if (drv["ValueList"] != System.DBNull.Value)
                            {
                                string[] arrElems = null;
                                arrElems = Regex.Split(drv["ValueList"].ToString(), ";");

                                drp.Items.Add(new ListItem("", ""));
                                for (int i = 0; i < arrElems.Length; ++i)
                                    drp.Items.Add(new ListItem(arrElems[i], i.ToString()));

                                if (dv_Results.Count > 0)
                                {
                                    foreach (ListItem li in drp.Items)
                                    {
                                        if (0 == String.Compare(li.Value, dv_Results[0]["stringValue"].ToString()))
                                            drp.SelectedValue = li.Value;
                                    }
                                }
                            }
                            plcModifyResults.Controls.Add(drp);
                            break;
                        }

                    case "TXT":
                        {
                            TextBox txt = new TextBox();
                            txt.ID = "txtTXT" + drv["RefID"].ToString();
                            txt.TextMode = TextBoxMode.MultiLine;
                            txt.Height = 15;
                            txt.Width = 100;
                            if (dv_Results.Count > 0)
                                txt.Text = dv_Results[0]["stringValue"].ToString();
                            plcModifyResults.Controls.Add(txt);
                            if (drv["UMName"] != System.DBNull.Value)
                                plcModifyResults.Controls.Add(new LiteralControl("<span class=\"redFont\">" + drv["UMName"].ToString().Replace("[", "<").Replace("]", ">") + "</span>"));
                            break;
                        }

                    case "STR":
                        {
                            TextBox txt = new TextBox();
                            txt.ID = "txtSTR" + drv["RefID"].ToString();
                            txt.Width = 100;
                            if (dv_Results.Count > 0)
                                txt.Text = dv_Results[0]["stringValue"].ToString();
                            plcModifyResults.Controls.Add(txt);
                            if (drv["UMName"] != System.DBNull.Value)
                                plcModifyResults.Controls.Add(new LiteralControl("<span class=\"redFont\">" + drv["UMName"].ToString().Replace("[", "<").Replace("]", ">") + "</span>"));

                            break;
                        }
                }

                plcModifyResults.Controls.Add(new LiteralControl("</td>"));
                plcModifyResults.Controls.Add(new LiteralControl("<td style=\"width: 30%\">"));

                TextBox txtCom = new TextBox();
                txtCom.ID = "txtComments" + drv["RefID"].ToString();
                txtCom.TextMode = TextBoxMode.MultiLine;
                txtCom.Height = 15;
                txtCom.Width = 250;

                if (dv_Results.Count > 0)
                    txtCom.Text = dv_Results[0]["Comments"].ToString();
                else
                    txtCom.Text = "";

                plcModifyResults.Controls.Add(txtCom);
                plcModifyResults.Controls.Add(new LiteralControl("</td>"));
                plcModifyResults.Controls.Add(new LiteralControl("</tr>"));
            }

            plcModifyResults.Controls.Add(new LiteralControl("</table>"));

            if (bSave)
            {
                foreach (DataRowView drv in dv_ModifySelect)
                {
                    sqlResults = @"select [ID], stringValue, Comments from Results where AnalyseID =" + drv["AnalyseID"].ToString() + " and RefID=" + drv["RefID"].ToString();
                    ds_Results = Hipocrate.DB.DBConnection.GetData(sqlResults);
                    dv_Results = ds_Results.Tables[0].DefaultView;

                    foreach (Control ctrl in plcModifyResults.Controls)
                    {
                        string sValue = "";
                        string sComments = "";
                        int x;
                        if (ctrl is TextBox && ctrl.ID == "txtINT" + drv["RefID"].ToString())
                        {
                            sValue = Request.Form[ctrl.UniqueID];
                            if (plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 3] is TextBox)
                                sComments = Request.Form[plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 3].UniqueID];
                            else if (plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 4] is TextBox)
                                sComments = Request.Form[plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 4].UniqueID];

                        }
                        else if (ctrl is DropDownList && ctrl.ID == "drpLST" + drv["RefID"].ToString())
                        {
                            sValue = Request.Form[ctrl.UniqueID];
                            if (plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 3] is TextBox)
                                sComments = Request.Form[plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 3].UniqueID];
                            else if (plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 4] is TextBox)
                                sComments = Request.Form[plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 4].UniqueID];
                        }
                        else if (ctrl is TextBox && ctrl.ID == "txtTXT" + drv["RefID"].ToString())
                        {
                            sValue = Request.Form[ctrl.UniqueID];
                            if (plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 3] is TextBox)
                                sComments = Request.Form[plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 3].UniqueID];
                            else if (plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 4] is TextBox)
                                sComments = Request.Form[plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 4].UniqueID];
                        }
                        else if (ctrl is TextBox && ctrl.ID == "txtSTR" + drv["RefID"].ToString())
                        {
                            sValue = Request.Form[ctrl.UniqueID];
                            if (plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 3] is TextBox)
                                sComments = Request.Form[plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 3].UniqueID];
                            else if (plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 4] is TextBox)
                                sComments = Request.Form[plcModifyResults.Controls[plcModifyResults.Controls.IndexOf(ctrl) + 4].UniqueID];
                        }

                        if (dv_Results.Count > 0 && !string.IsNullOrEmpty(sValue))
                        {
                            x = Hipocrate.DB.DBConnection.Execute("Results_Save",
                             new string[] { "@intCodeID", "@strAnalyseID", "@strUserID", "@strRefID", "@strStringValue", "@strComments", "@changedDate" },
                             new object[] { dv_Results[0]["ID"], drv["AnalyseID"], Tools.StaffID, drv["RefID"], sValue, sComments, null });
                        }
                        else if (!string.IsNullOrEmpty(sValue))
                        {
                            x = Hipocrate.DB.DBConnection.Execute("Results_Save",
                                new string[] { "@strAnalyseID", "@strUserID", "@strRefID", "@strStringValue", "@strComments", "@changedDate" },
                                new object[] { drv["AnalyseID"], Tools.StaffID, drv["RefID"], sValue, sComments, null });
                        }
                    }
                }

                btnBackInvestigation_Click(null, null);
                this.SetMessage("Datele au fost salvate!", false);
            }
        }
        catch (Exception ex)
        {
			this.SetMessage("[Modify]" + ex.Message, true);
        }
    }

    protected void BuletinRedirect_Click(object sender, EventArgs e)
    {
        LinkButton lnk = sender as LinkButton;
        string className = lnk.CommandArgument;
        Response.Redirect("Reports/BuletinAnalyse.aspx?requestID=" + requestID + "&class=" + className, false);
    }

    protected void btnSaveModified_Click(object sender, EventArgs e)
    {
        ModifyResults(true, strAnalyseClass);
    }

    protected void btnAddInvestigation_Click(object sender, EventArgs e)
    {
		//tabSpecificRequest.Visible = true;
		tabSpecificRequest.HeaderText = "Cerere Noua";
		tabContainer.ActiveTab = tabSpecificRequest;
		requestID = null;

		divAddInvestigation.Style.Add("display", "block");
		//divResultsSearch.Style.Add("display", "none");
        divDetailsRequest.Style.Add("display", "none");
        divTestRequest.Style.Add("display", "none");
		SetAnalyseListVisibility(false);
		divModifyResults.Style.Add("display", "none");
        //btnAddInvestigation.Visible = false;
		//output.Text += "showing button @ btnAddInvestigation_Click. ";
		btnSaveInvestigation.Visible = true;

        txtINVDate.Text = System.DateTime.Now.ToShortDateString();
        drpInvSex.Items.Clear();
        drpInvSex.Items.Add(new ListItem(""));
        drpInvSex.Items.Add(new ListItem("Masculin"));
        drpInvSex.Items.Add(new ListItem("Feminin"));

        DataSet ds_Judet = Hipocrate.DB.DBConnection.GetData(@"select * from DRG_DISTRICTS order by JudetNume");
        DataView dv_Judet = ds_Judet.Tables[0].DefaultView;

        drpJudet.DataSource = dv_Judet;
        drpJudet.DataTextField = "judetnume";
        drpJudet.DataValueField = "id";
        drpJudet.DataBind();
        drpJudet.Items.Insert(0, "");

        DataSet ds_TypeMedic = Hipocrate.DB.DBConnection.GetData(@"select ID, Type from MEDIC_TYPES");
        DataView dv_TypeMedic = ds_TypeMedic.Tables[0].DefaultView;

        drpInvMedic.DataSource = dv_TypeMedic;
        drpInvMedic.DataTextField = "type";
        drpInvMedic.DataValueField = "id";
        drpInvMedic.DataBind();

        DataSet ds_Medic = Hipocrate.DB.DBConnection.GetData(@"select distinct ID, FullName, RequestPwdOnSelect from vMedics order by FullName");
        DataView dv_Medic = ds_Medic.Tables[0].DefaultView;

        drpInvMedicul.DataSource = dv_Medic;
        drpInvMedicul.DataTextField = "FullName";
        drpInvMedicul.DataValueField = "id";
        drpInvMedicul.DataBind();
        drpInvMedicul.Items.Insert(0, "");

        DataSet ds_Payment = Hipocrate.DB.DBConnection.GetData(@"select ID, Name from PAYMENT_TYPES where Active=1 order by Name");
        DataView dv_Payment = ds_Payment.Tables[0].DefaultView;

        drpInvPayment.DataSource = dv_Payment;
        drpInvPayment.DataTextField = "name";
        drpInvPayment.DataValueField = "id";
        drpInvPayment.DataBind();
    }

    protected void districtZone_IndexChanged(object sender, EventArgs e)
    {
        if (drpJudet.SelectedIndex > 0)
        {
            string zoneID = drpJudet.SelectedValue;

            string sql = "SELECT * FROM drg_city WHERE LocalitateJudet_ID = " + zoneID;

            if (txtCityName.Text.Length > 0)
                sql += " AND LocalitateNume LIKE '%" + txtCityName.Text.Replace("'", "''") + "%' ";
            if (strCityType.SelectedIndex > 0)
                sql += " AND LocalitateUrbanRural = '" + strCityType.SelectedValue + "'";
            string drgCode = strDRGCode.Text.Trim();
            if (drgCode.Length > 0)
                sql += " AND Localitate_cod LIKE '%" + drgCode.Replace("'", "''") + "%' ";

            sql += " ORDER BY LocalitateNume";

            DataSet ds = Hipocrate.DB.DBConnection.GetData(sql);
            rptResultsLocalitate.DataSource = ds;
            rptResultsLocalitate.DataBind();

            mdlPopupDistrict.Show();
        }
        else
        {
            this.SetMessage("Va rugam selectati mai intai judetul!", false);
            drpJudet.Focus();
        }
    }

    protected void repeaterResultsLocalitate_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Footer) || (e.Item.ItemType == ListItemType.Header))
            return;
        DataRowView row = e.Item.DataItem as DataRowView;
        string cmdArg = (row["LocalitateNume"]).ToString() + ";" + (row["LocalitateUrbanRural"]).ToString() + ";" + (row["Localitate_Cod"]).ToString();

        foreach (Control c in e.Item.Controls)
        {
            if (c is LinkButton)
                (c as LinkButton).CommandArgument = cmdArg;
        }
    }

    protected void imgLinkZoneName_Click(object sender, EventArgs e)
    {
        districtZone_IndexChanged(null, null);
    }

    protected void btnCautaLocalitate_Click(object sender, EventArgs e)
    {
        if (sender != null)
            districtZone_IndexChanged(null, null);
    }

    protected void SelectLocalitate(object sender, EventArgs e)
    {
        mdlPopupDistrict.Hide();
        if (sender != null)
        {
            LinkButton lnk = sender as LinkButton;
            string[] info = lnk.CommandArgument.ToString().Split(';');
            txtLocalitate.Text = info[0];
            strCityType.SelectedValue = (info[1].Equals("u") ? "(urban)" : info[1].Equals("r") ? "(rural)" : info[1]);
        }
    }

    protected string GetColourForSetElementType(string strType)
    {
        return (strType.Equals("u") ? "red" : strType.Equals("r") ? "green" : "gray");
    }

	/// <summary>
	/// temporary copy of LoadDetailsRequest to help with putting together the Save method below...
	/// </summary>
	private void ExistingDetailsRequest()
	{
		//ds_DetailsPacient: "GrSang", "rh", "Sex", "Age", "CIID"
		//ds_LabRequest: ...

/**/		DataSet ds_LabRequest = Hipocrate.DB.DBConnection.GetData(@"select LAB_REQUESTS.*,
					pt.Name as PaymentTypeName,death.MedicSuperviserID,
                    convert(varchar(10), death.RegistredDate, 103) deathReqDate,
                    convert(varchar(5),death.RegistredDate,108) as deathRecTime,
                     convert(varchar(20), RequestedDate, 113) RequestedDate,
                     convert(varchar(10), RequestedDate, 103) ReqDate,
                     convert(varchar(5), RequestedDate, 108) ReqTime,
                     convert(varchar(20), VisibleDate, 113) strVisibleDate,
                     convert(varchar(20), DeletedDate, 113) DeletedDate, DeletedID,
                     convert(varchar(20), CompletedDate, 113) CompletedDate
                    from LAB_REQUESTS
                    left join payment_types pt on LAB_REQUESTS.PaymentTypeID=pt.id
                    left join lab_deathrecords death on death.requestID=LAB_REQUESTS.id
                    where LAB_REQUESTS.[id]=" + requestID + "");
/**/		DataView dv2 = ds_LabRequest.Tables[0].DefaultView;

/**/		string sqlLabRequest;
/**/		DataSet dsLRQ = null;

/**/		if (strExternalType == "PA")
/**/			sqlLabRequest = "";
/**/		else if (strExternalType == "PR" || strExternalType == "P")
/**/		{
/**/			sqlLabRequest = "select sDeclaredDate as sDate, sDeclaredTime as sTime, SectionName, MedicFullName, MedicID from vPresentationFull where ID=" + strExternalID;
/**/			dsLRQ = Hipocrate.DB.DBConnection.GetData(sqlLabRequest);
/**/			strMedicID = dsLRQ.Tables[0].Rows[0]["MedicID"].ToString();
/**/		}
/**/		else if (strExternalType == "CI")
/**/		{
/**/			sqlLabRequest = "select sCIDate as sDate, sCITime as sTime, SectionName, MedicFullName, CIMedicID as MedicID from vCheckIn_LabRequests where CIID=" + strExternalID;
/**/			dsLRQ = Hipocrate.DB.DBConnection.GetData(sqlLabRequest);
/**/			strMedicID = dsLRQ.Tables[0].Rows[0]["MedicID"].ToString();
/**/		}
/**/		else if (strExternalType == "CU")
/**/		{
/**/			sqlLabRequest = "select sCUDate as sDate, sCUTime as sTime, SectionName, MedicFullName, CUMedic as MedicID from vCheckUpFull where CUID=" + strExternalID;
/**/			dsLRQ = Hipocrate.DB.DBConnection.GetData(sqlLabRequest);
/**/			strMedicID = dsLRQ.Tables[0].Rows[0]["MedicID"].ToString();
/**/		}
/**/		else if (strExternalType == "CO")
/**/		{
/**/			sqlLabRequest = "select sCODate as sDate, sCOTime as sTime, SectionName, MedicFullName, COMedicID as MedicID from vCheckOutFull where COID=" + strExternalID;
/**/			dsLRQ = Hipocrate.DB.DBConnection.GetData(sqlLabRequest);
/**/			strMedicID = dsLRQ.Tables[0].Rows[0]["MedicID"].ToString();
/**/		}
/**/		else
/**/			sqlLabRequest = "";


/**/		DataSet dsValidatorID = null;
/**/		if (!string.IsNullOrEmpty(dv2[0]["DeletedDate"].ToString()))
/**/		{
/**/			lblValAnul.Text = "Anulata";
/**/			string sqlRequestordeletedID = "select isnull(lastname, '') + isnull(upper(' ' + firstname), '') as name from staff where id=" + dv2[0]["DeletedID"].ToString();
/**/			DataSet dsStatusRequestor = Hipocrate.DB.DBConnection.GetData(sqlRequestordeletedID);
/**/			if (dsStatusRequestor.Tables.Count > 0)
/**/				lblStatus.Text = "<span class=\"redFont\">" + dsStatusRequestor.Tables[0].Rows[0]["name"].ToString() + "</span>&nbsp;-&nbsp;" + dv2[0]["DeletedDate"].ToString() + "";
/**/			else
/**/				lblStatus.Text = "INEXISTENT" + "&nbsp;-&nbsp;" + dv2[0]["DeletedDate"].ToString() + "";
/**/		}
/**/		else
/**/		{
/**/			string sqlValidatorID = @"select convert(varchar(20), LS.ValidationDate, 113) ValidationDate, LS.ValidatorID, LS.SectionCode from LAB_SECTIONS LS 
                                where LS.RequestID=" + requestID;
/**/			dsValidatorID = Hipocrate.DB.DBConnection.GetData(sqlValidatorID);
/**/			string validatorID = null;
/**/			if (dsValidatorID.Tables[0].Rows.Count > 0)
/**/				validatorID = dsValidatorID.Tables[0].Rows[0]["ValidatorID"].ToString();
/**/			if (string.IsNullOrEmpty(validatorID))
/**/			{
/**/				lblValAnul.Text = "Nevalidata";
/**/			}
/**/			else
/**/			{
/**/				lblValAnul.Text = "Validata";
/**/				string sqlRequestordeletedID = @"select isnull(lastname, '') + isnull(upper(' ' + firstname), '') as name
											from staff where id=" + validatorID;
/**/				DataSet dsStatusRequestor = Hipocrate.DB.DBConnection.GetData(sqlRequestordeletedID);

/**/				string strValidatorsString = @"<SPAN STYLE='WIDTH: 200px'>" + dsStatusRequestor.Tables[0].Rows[0]["name"].ToString() + "</SPAN>" +
/**/					"&nbsp;-&nbsp;" + dsValidatorID.Tables[0].Rows[0]["ValidationDate"].ToString() +
/**/					"&nbsp;, " + dsValidatorID.Tables[0].Rows[0]["SectionCode"].ToString();

/**/				lblStatus.Text = strValidatorsString;
/**/			}

/**/			if (!string.IsNullOrEmpty(dv2[0]["CompletedDate"].ToString()))
/**/			{
/**/				lblCompleted.Text = "&nbsp;PROCESATA&nbsp;-&nbsp;" + dv2[0]["CompletedDate"].ToString();
/**/			}
/**/			else
/**/			{
/**/				if (!string.IsNullOrEmpty(dv2[0]["DeletedDate"].ToString()))
/**/					lblCompleted.Text = "ANULATA";
/**/				else if (!string.IsNullOrEmpty(dv2[0]["strVisibleDate"].ToString()))
/**/					lblCompleted.Text = "Trimisa pe sectie";
/**/				else if (!string.IsNullOrEmpty(dv2[0]["ClosedID"].ToString()))
/**/					lblCompleted.Text = "<font class='error'>INCHISA</font>";
/**/				else if (dsValidatorID.Tables.Count > 0)
/**/					lblCompleted.Text = "Validata pentru executie";
/**/				else if (!string.IsNullOrEmpty(dv2[0]["Submited"].ToString()))
/**/					lblCompleted.Text = "Trimisa spre executie";
/**/				else
/**/					lblCompleted.Text = "<font class='blueFont'>Nu va fi procesata, nefiind inca trimisa spre executie!</font>";
/**/			}
/**/		}


/**/		txtWeight.Text = dv2[0]["Weigth"].ToString();
/**/		txtHeight.Text = dv2[0]["Height"].ToString();

/**/		lblDateRequest.Text = dv2[0]["ReqDate"].ToString() + "&nbsp" + dv2[0]["ReqTime"].ToString();

/**/		foreach (ListItem li in drpPayment.Items)
/**/		{
/**/			if (0 == String.Compare(li.Value, paymentTypeID))
/**/				drpPayment.SelectedValue = li.Value;
/**/		}

/**/		string sqlDeathDate = @"select RecordDeathData from lab_sections ls left join sections s on ls.sectioncode=s.code where requestid=" + requestID;
/**/		DataSet ds_DeathDate = Hipocrate.DB.DBConnection.GetData(sqlDeathDate);
/**/		DataView dvDeathDate = ds_DeathDate.Tables[0].DefaultView;
/**/		if ((dvDeathDate.Count > 0) && (dvDeathDate[0]["RecordDeathData"].ToString() == "0"))
/**/		{
/**/			string sqlMedicSurviver = @"select ID,LastName+ ' ' + FirstName as MedicName  from staff s where s.sectioncode<>'EXT' and exists 
                                        (select * from staffpositions sp left join positions p on sp.PosCode=p.code 
                                        where (p.code='MEDIC' or p.code='MED') and s.id=sp.staffid)";
/**/			DataSet ds_MedicSurviver = Hipocrate.DB.DBConnection.GetData(sqlMedicSurviver);
/**/			DataView dvMedicSurviver = ds_MedicSurviver.Tables[0].DefaultView;

/**/			drpMedicSurviver.DataSource = dvMedicSurviver;
/**/			drpMedicSurviver.DataTextField = "medicname";
/**/			drpMedicSurviver.DataValueField = "id";
/**/			drpMedicSurviver.DataBind();
/**/			drpMedicSurviver.Items.Insert(0, "");

/**/			foreach (ListItem li in drpMedicSurviver.Items)
/**/			{
/**/				if (0 == String.Compare(li.Value, dv2[0]["MedicSuperviserID"].ToString()))
/**/					drpMedicSurviver.SelectedValue = li.Value;
/**/			}

/**/			trDeath.Style.Add("display", "block");
/**/			plcDeath.Controls.Add(drpMedicSurviver);
/**/			plcDeath.Controls.Add(new LiteralControl(dv2[0]["deathReqDate"].ToString() + "&nbsp" + dv2[0]["deathRecTime"].ToString()));
/**/		}

/**/		string sqlPacientSex = @"select Sex, datediff(Y, GetDate(), BirthDate) as Age, CIID from pacients where [id]=" + pacientID;
/**/		DataSet ds_PacientSex = Hipocrate.DB.DBConnection.GetData(sqlPacientSex);
/**/		DataView dvPacientSex = ds_PacientSex.Tables[0].DefaultView;

/**/		if (dv2[0]["Submited"].ToString() != "True")
/**/		{
/**/			trSection.Style.Add("display", "block");
/**/			string sqlCodeSection = @"select distinct s.code, s.name from sections s join lab_domains l on s.code=l.section where l.active=1 and s.Active=1 order by s.name";
/**/			DataSet ds_CodeSection = Hipocrate.DB.DBConnection.GetData(sqlCodeSection);
/**/			DataView dvCodeSection = ds_CodeSection.Tables[0].DefaultView;

/**/			string sqlCountSection = @"select count(*) as NR from vAnalysesSelected v join lab_domains l on v.Class=l.Domain where v.RequestID=35464 and l.Section=
                                '" + dvCodeSection[0]["code"].ToString() + "'";
/**/			DataSet ds_CountSection = Hipocrate.DB.DBConnection.GetData(sqlCountSection);
/**/			DataView dvCountSection = ds_CountSection.Tables[0].DefaultView;

/**/			string sqlNameSection = @"select * from lab_sections where requestID=
                                " + requestID + " and SectionCode='" + dvCodeSection[0]["code"].ToString() + "'";
/**/			DataSet ds_NameSection = Hipocrate.DB.DBConnection.GetData(sqlNameSection);
/**/			DataView dvNameSection = ds_NameSection.Tables[0].DefaultView;

/**/			plcSection.Controls.Add(new LiteralControl("<input name=\"strSections\" id=\"strSections\" type=\"checkbox\" checked=\"checked\" value=\" " + dvCodeSection[0]["code"].ToString() + "\" ><label for=\"strSections\">&nbsp;<b>" + dvCodeSection[0]["name"].ToString() + "</b></label>"));
/**/		}

/**/		string sqlstrPreviousCT = @"select * from LAB_SECTIONS where RequestID=" + requestID + " AND SectionCode='CT'";
/**/		DataSet ds_strPreviousCT = Hipocrate.DB.DBConnection.GetData(sqlstrPreviousCT);
/**/		DataView dvstrPreviousCT = ds_strPreviousCT.Tables[0].DefaultView;


/**/		string sqlQuickLnk = @"select L.ID, CONVERT(VARCHAR(6), L.RequestedDate, 113) as ReqDate from lab_requests L 
                    where L.PacientID=" + pacientID + " AND L.[ID]<>" + requestID + " AND EXISTS (select * from lab_sections LS where ls.RequestID=L.[ID])";

/**/		DataSet ds_QuickLnk = Hipocrate.DB.DBConnection.GetData(sqlQuickLnk);
/**/		DataView dvQuickLnk = ds_QuickLnk.Tables[0].DefaultView;

/**/		for (int i = 0; i < dvQuickLnk.Count; i++)
/**/		{
/**/			plkQuickLink.Controls.Add(new LiteralControl("&nbsp;" + dvQuickLnk[0]["ID"].ToString() + "&nbsp;"));
/**/		}

/**/		if (!string.IsNullOrEmpty(paymentTypeID))
/**/		{
/**/			string sqlRequestCost = @"select SUM(ISNULL(Qty, 0)*ISNULL(Price, 0)) as analyseCost from vAnalyseType_Costs 
            join analyses on vAnalyseType_Costs.ID=analyses.TypeID 
            where requestID=" + requestID + " AND CONVERT(DATETIME, '" + ((DateTime)(dv2[0]["RequestedDate"])).ToString("dd/MM/yyyy") + "' , 103) between startDate AND ISNULL(endDate, GetDate()) " +
/**/			" AND (endDate IS NULL OR GetDate() between startDate AND endDate)" +
/**/			" AND analyses.PaymentTypeID= " + paymentTypeID + " AND vAnalyseType_Costs.PaymentTypeID=" + paymentTypeID;

/**/			DataSet ds_RequestCost = Hipocrate.DB.DBConnection.GetData(sqlRequestCost);
/**/			DataView dvRequestCost = ds_RequestCost.Tables[0].DefaultView;

/**/			if (dvRequestCost.Count > 0)
/**/			{
/**/				object dbCost = dvRequestCost[0]["AnalyseCost"];
/**/				if (dbCost == DBNull.Value) dbCost = 0;
/**/				double tempCost = Convert.ToDouble(dbCost);
/**/				lblCosts.Text = tempCost.ToString();
/**/			}
/**/			else
/**/				lblCosts.Text = "";
/**/		}
/**/		else
/**/		{
/**/			string sqlRequestCostAnalyse = @"select TypeID, PaymentTypeID from ANALYSES where RequestID=" + requestID;

/**/			DataSet ds_RequestCostAnalyse = Hipocrate.DB.DBConnection.GetData(sqlRequestCostAnalyse);
/**/			DataView dvRequestCostAnalyse = ds_RequestCostAnalyse.Tables[0].DefaultView;

/**/			double tmpCostAnalyse = 0;

/**/			for (int i = 0; i < dvRequestCostAnalyse.Count; ++i)
/**/			{
/**/				tmpCostAnalyse += getTotalCost(dvRequestCostAnalyse[0]["TypeID"].ToString(), dv2[0]["RequestedDate"].ToString(), dv2[0]["PaymentTypeID"].ToString());
/**/			}
/**/		}
	}
	protected void btnSaveInvestigation_Click(object sender, EventArgs e)
    {
        try
        {
            string strMedicId = drpInvMedicul.SelectedValue;
            if (rInvMedic.Checked)
                strMedicId = drpInvMedicul.SelectedValue;

            strExternalType = "PA";
            strExternalID = "0";

			object[] requestValues = null;
            object reqId = Tools.GetSQLValue(requestID);
            if (reqId == DBNull.Value)
			{
                requestValues = new object[] { reqId, //as: "@intCodeID",
					//"@strPacientID", "@strExternalID", "@strExternalType", "@strPaymentTypeID",
					pacientID, strExternalID, strExternalType, Tools.GetSQLValue(drpInvPayment.SelectedValue),
					//"@strPaymentNo", "@strSentDiags", "@strResponseDiags", "@strCustID",
					Tools.GetSQLValue(txtInvReg.Text), Tools.GetSQLValue(txtInvDiagnostic.Text), null, null,
					//"@strMedicID", "@strSampleID",
					Tools.GetSQLValue(strMedicId), 0,
					//"@strRequestorID", "@strRequestedDate",
					Tools.StaffID, CommonSession.StareDiagramaIndicatori.GetDate(txtINVDate).ToString(),
					//"@strIsPregnant", "@strPriority",
					null, chkInvUrgency.Checked == true ? 1 : 0,
					//"@strDescription", "@strCheckedIn", "@strOtherDiagsOff",
					Tools.GetSQLValue(txtInvInfSuplim.Text), null, null,
					//"@strPreviousCT", "@strIodOK", "@strUserLogin",
					null, null, Tools.userLogin,
					//"@nrChit", "@serieTrimitere", "@nrTrimitere", "@dataTrimitere"
					Tools.GetSQLValue(txtInvChit.Text), null, null, null,
					//"@strWeigth", "@strHeight"
					Tools.GetSQLValue(txtInvWeight.Text), Tools.GetSQLValue(txtInvHeight.Text)
				};
			}
			else
			{
                requestValues = new object[] { reqId, //as: "@intCodeID",
					//"@strPacientID", "@strExternalID", "@strExternalType", "@strPaymentTypeID",
					pacientID, strExternalID, strExternalType, paymentTypeID,
					//"@strPaymentNo", "@strSentDiags", "@strResponseDiags", "@strCustID",
					Tools.GetSQLValue(txtRegister.Text), Tools.GetSQLValue(txtSentDiags.Text), Tools.GetSQLValue(txtDiagnostic.Text), null,
					//"@strMedicID", "@strSampleID",
					Tools.GetSQLValue(strMedicId), 0,
					//"@strRequestorID", "@strRequestedDate",
					strRequestorID, requestedDate,
					//"@strIsPregnant", "@strPriority",
					(lblInsarcinata.Text.Length > 6 ? 1 : 0), strPriority,
					//"@strDescription", "@strCheckedIn", "@strOtherDiagsOff",
					Tools.GetSQLValue(txtDescription.Text), lblCheckedIn.Text.Equals("DA") ? 1 : 0, lblOtherDiagsOff.Text.Equals("DA") ? 1 : 0,
					//"@strPreviousCT", "@strIodOK", "@strUserLogin",
					lblPreviousCT.Text.Equals("DA") ? 1 : 0, lblIodOK.Text.Equals("DA") ? 1 : 0, Tools.userLogin,
					//"@nrChit", "@serieTrimitere", "@nrTrimitere", "@dataTrimitere"
					Tools.GetSQLValue(txtChitanta.Text), null, null, null,
					//"@strWeigth", "@strHeight"
					Tools.GetSQLValue(txtWeight.Text), Tools.GetSQLValue(txtHeight.Text)
				};
				//TODO: add missing data:
				//"@Test" := chkProbeTech.Checked
				//"@IsPayed" := chkAchitat.Checked
				//"@Comments" := txtCommnets.Text
			}

            //output.Text += " ... LabRequest_Save ";
            //foreach (object o in requestValues)
            //    output.Text += (o == null) || (o == DBNull.Value) ? "NULL, " : string.Format("'{0}', ", o);
            //output.Text = output.Text.TrimEnd(' ', ',');
           
            object outputValue = Hipocrate.DB.DBConnection.ExecuteSPWithInOutParams("LabRequest_Save",
				new string[] { "@intCodeID",
					"@strPacientID", "@strExternalID", "@strExternalType", "@strPaymentTypeID",
					"@strPaymentNo", "@strSentDiags", "@strResponseDiags", "@strCustID",
					"@strMedicID", "@strSampleID",
					"@strRequestorID", "@strRequestedDate", "@strIsPregnant", "@strPriority",
					"@strDescription", "@strCheckedIn", "@strOtherDiagsOff",
					"@strPreviousCT", "@strIodOK", "@strUserLogin",
					"@nrChit", "@serieTrimitere", "@nrTrimitere", "@dataTrimitere",
					"@strWeigth", "@strHeight"},
				requestValues, "@strOUT")[0].Value;

            this.SetMessage("Datele au fost salvate!", false);
			//TODO: show direct link!
        }
        catch (Exception ex)
        {
			this.SetMessage("[Save]" + ex.Message, false);
        }
    }

    protected string getSex(string sex)
    {
        if (sex == "True")
            return "M";
        else if (sex == "False")
            return "F";
        else
            return "";
    }

    protected void imgPatientName_Click(object sender, EventArgs e)
    {
        try
        {
            if (!string.IsNullOrEmpty(txtInvName.Text))
            {
                DataSet dsPatients = Hipocrate.DB.DBConnection.GetData("Pacient_Identify", new string[] { "@strName1", "@strName2", "@strBirthDate", "@strCNP", "@strSex", },
                    new object[] { Tools.GetSQLValue(txtInvName.Text), Tools.GetSQLValue(txtInvSurname.Text), null, Tools.GetSQLValue(txtInvCNP.Text), null });
                DataView dvPatient = dsPatients.Tables[0].DefaultView;

                rptResultsPatient.DataSource = dvPatient;
                rptResultsPatient.DataBind();

                mdlPopupPatient.Show();
            }
            else
            {
                this.SetMessage("Va rugam introduceti un nume!", true);
                txtInvName.Focus();
            }
        }
        catch (Exception ex)
        {
			this.SetMessage("[PatName]" + ex.Message, true);
        }
    }

    protected void rptPatient_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if ((e.Item.ItemType == ListItemType.Footer) || (e.Item.ItemType == ListItemType.Header))
            return;
        DataRowView row = e.Item.DataItem as DataRowView;
        string cmdArg = (row["FirstName"]).ToString() + ";" + (row["LastName"]).ToString() + ";" + (row["CNP"]).ToString() + ";" + (row["Zone"]).ToString() + ";" + (row["ID"]).ToString();

        foreach (Control c in e.Item.Controls)
        {
            if (c is LinkButton)
                (c as LinkButton).CommandArgument = cmdArg;
        }
    }

    protected void SelectPatient(object sender, EventArgs e)
    {
        mdlPopupPatient.Hide();
        if (sender != null)
        {
            LinkButton lnk = sender as LinkButton;
            string[] info = lnk.CommandArgument.ToString().Split(';');
            txtInvName.Text = info[0];
            txtInvSurname.Text = info[1];
            txtInvCNP.Text = info[2];
            string zone = info[3];
            pacientID = info[4];

            string js = "cl_validate()";
            ScriptManager.RegisterStartupScript(this, typeof(LabRequest), "cl_validate", js, true);
            int countSelected = 0;
            foreach (ListItem li in drpJudet.Items)
            { 
                if (0 == String.Compare(li.Text, zone))
                {
                    drpJudet.SelectedIndex = countSelected;
                } 
                countSelected++;
            }

            districtZone_IndexChanged(null, null);
        }
    }

	protected void bulkProcessing_Click(object sender, EventArgs e)
	{
		List<string> parameters = new List<string>();
		parameters.Add("action=" + bulkProcessing.Text.Substring(0, 5).TrimEnd('i'));
		if (strIDS.Text.Trim().Length > 0)
			parameters.Add("IDS=" + strIDS.Text);
		if (strStartDateBulk.Text.Trim().Length > 0)
			parameters.Add("SD=" + GetMiniDate(strStartDateBulk.Text));
		if (strEndDateBulk.Text.Trim().Length > 0)
			parameters.Add("ED=" + GetMiniDate(strEndDateBulk.Text));
		if (strSectionBulk.SelectedIndex > 0)
			parameters.Add("Section=" + strSectionBulk.SelectedValue);
		if (strMedicBulk.SelectedIndex > 0)
			parameters.Add("Medic=" + strMedicBulk.SelectedValue);
		if (strLabDomainsBulk.SelectedIndex > 0)
			parameters.Add("LabDomains=" + strLabDomainsBulk.SelectedValue);
		string url = "BulkProcessing.aspx";
		if (parameters.Count > 0)
			url += "?" + parameters.Join("&");
		processingResults.Attributes["src"] = url; //it's a mere "HtmlGenericControl" (which inherits: HtmlContainerControl : HtmlControl : Control)
	}
	private string GetMiniDate(string input)
	{
		try
		{
			return Tools.GetDateTime(input, DateFormat).ToString("yyyyMMdd");
		}
		catch (ApplicationException)
		{
			return input;
		}
	}
	private string DateFormat = "dd/MM/yyyy";
}
